这是在Java中重复方法调用的最干净的方法吗? [英] Is this the cleanest way to repeat method call in Java?
本文介绍了这是在Java中重复方法调用的最干净的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下内容看起来像是凌乱的代码,但我想不出如何使其更整洁。有任何想法吗?我想为10、20和30的值调用doSearch。如果没有返回任何值的结果,那么我想尝试以下值。否则,请退出。我知道这行得通,但这是最可读的方法吗?
The following looks like messy code, but I can't think how to make it neater. Any ideas? I want to call doSearch for values of 10, 20 and 30. If no results are returned for a value, then I want to try for the following value. Otherwise, just exit out. I know this would work, but is it the most readable way?
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
}
}
}
推荐答案
这里是一个建议:
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在评论中所建议。)
(as suggested by Marko Topolnik in the comments.)
这篇关于这是在Java中重复方法调用的最干净的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文