重构一个方法,如果抛出异常则返回 false。

huangapple go评论77阅读模式
英文:

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

问题

我有这个方法,它只应在列表中的所有项目(List<Foo> foos)的所有项目中都没有异常发生时返回true:

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

其中checkConnection是一个可以抛出异常的void方法:

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

我想重构isHealthy,使其看起来更可读,因为从catch块返回的样子不太优雅,即使该方法只有9行,乍一看也不清楚它如何处理嵌套的try-for-catch块。在这种情况下,是否有一些Java 8功能(Optionals、streams等)可以帮助?

英文:

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?

答案1

得分: 3

我会把翻译好的内容返回给你,如下:

我会将每个Foo的连接检查委派到一个单独的方法中,该方法包装在try-catch块中,根据连接结果返回boolean值:

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

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

使用Stream::allMatch方法进行健康检查本身变得非常简单和易读,它检查所有连接检查是否均为true

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

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&lt;Foo&gt; foos = ...
    return foos.stream().allMatch(this::isConnected);
}

huangapple
  • 本文由 发表于 2020年7月24日 19:05:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63072304.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定