Is this the cleanest way to repeat method call in Java?

馋奶兔 提交于 2019-12-23 21:25:35

问题


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
    }
  }
}

回答1:


Here's a suggestion:

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
}

(as suggested by Marko Topolnik in the comments.)




回答2:


You can store the search strings in a String[], then loop through the array and call doSearch().




回答3:


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



回答4:


I'd go with something like this:

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
}

Since numbers are numbers, I didn't think that iterating through their String representations is a good idea.



来源:https://stackoverflow.com/questions/10717458/is-this-the-cleanest-way-to-repeat-method-call-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!