英文:
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<Foo> foos = ...
return foos.stream().allMatch(this::isConnected);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论