Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
    }
  }
}
like image 902
edwardmlyte Avatar asked Jan 26 '26 07:01

edwardmlyte


2 Answers

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.)

like image 110
2 revsaioobe Avatar answered Jan 28 '26 21:01

2 revsaioobe


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

like image 24
nhahtdh Avatar answered Jan 28 '26 22:01

nhahtdh