nopens
nopens

Reputation: 761

Refactoring a method which returns false if an some exception is thrown

I have this method which should only return true when for all items in a list (List<Foo> foos) no exception occurs:

public boolean isHealthy(){
    try{
        for(final Foo myFoo : foos){
           checkConnection(myfoo);
        }
    }
    catch(DataAccessException | SQLException ex){
         return false;
    }
    return true;
} 

where checkConnection is a void method which can throw an exception

  void checkConnection(final Foo myFoo) throws SQLException{
      // ...
  }

I want to refactor isHealthy to make it some how readable because that return from a catch block looks not so elegant and even when the method has only 9 lines it is not obvious at first glance what it does with the nested try-for-catch block. Are there some java 8 features (Optionals, streams ..) which could help hier?

Upvotes: 0

Views: 119

Answers (1)

Nikolas
Nikolas

Reputation: 44418

I'd delegate a connection check wrapped in the try-catch for each Foo into a separate method returning boolean based on the connection result:

boolean isConnected(final Foo myFoo) {
    try {
        checkConnection(myFoo);
        return true;
    } catch(DataAccessException | SQLException ex) {
        return false;
    }
}

void checkConnection(final Foo myFoo) throws SQLException {
    // ...
}

The health check itselfs becomes fairly simple and readable using Stream::allMatch checking whether all connection checks are true.

public boolean isHealthy(){
    List<Foo> foos = ...
    return foos.stream().allMatch(this::isConnected);
}

Upvotes: 3

Related Questions