这是在Java中重复调用方法的最简洁方式吗?

3
以下代码看起来有些凌乱,但我想不到如何使它更整洁。有任何想法吗? 我想要对值为10、20和30调用doSearch。如果某个值没有返回结果,那么我想尝试下一个值。否则,退出程序。我知道这样可以实现,但这是最易读的方式吗?
SearchResult result = doSearch("10");
if (result.getResults() == null) {
  result = doSearch("20");
  if (result.getResults() == null) {
    result = doSearch("30");
    if (result.getResults() == null) {
      // put code to deal with lack of results here
    }
  }
}
4个回答

4
这里有一个建议:
SearchResult result = null;
for (String attempt : "10,20,30".split(","))
    if ((result = doSearch(attempt)) != null)
        break;

if (result == null) {
    // put code to deal with lack of results here
}

(根据Marko Topolnik在评论中的建议。)

检查 i >= attempts.length + 1 没有太多意义,因为它永远不可能评估为真。代码要么会因为 ArrayIndexOutOfBounds 而中断,要么检查返回 false。 - Marko Topolnik
int i; for (i = 0; i < attempts.length; i++) if ((result = doSearch(attempts[i])) != null) break; if (result == null) // put code to deal with lack of results here - Marko Topolnik
是的,for循环看起来更整洁了。谢谢大家。 - edwardmlyte
+1 很巧妙!如果使用 static import,你也可以这样写 String attempt : asList("10", "20", "30") - Marko Topolnik
啊,是的。我实际上会说这是少数几种情况之一,其中静态导入不会降低可读性 :-) - aioobe
是的,尝试导入Integer.valueOf以获得WTF效果 :) - Marko Topolnik

2
你可以将搜索字符串存储在String[]中,然后循环遍历该数组并调用doSearch()函数。

1
int [] searchValues = {10, 20, 30};


for(int i=0; i<searchValues.length; i++) {
   SearchResult result = doSearch(searchValues[i]);
   if (result.getResults() != null) {
       return result;
   }
}

// put code to deal with lack of results here

1
我会选择类似这样的东西:
SearchResult result = null;
for (int i=10; i<=30 && result == null; i+=10) {
    result = doSearch(i);
}
if (result == null) {
    // throw a meaningful business exception here
}

由于数字就是数字,我认为通过它们的字符串表示进行迭代并不是一个好主意。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接