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

The following looks like dirty code, but I can't think of how to make it more neat. Any ideas? I want to call doSearch for values ​​10, 20, and 30. If the results are not returned for the value, I want to try the following value. Otherwise, just exit. I know this will work, but is this 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
    }
  }
}
+3
source share
4 answers

Here is 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 Marco Topolnik in the comments.)

+4
source

You can save the search strings in String [], then skip the array and call doSearch ().

+2
source
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
}

Since numbers are numbers, I did not think that iterating through their representations of strings is a good idea.

+1
source

All Articles