我正在寻找一种优雅的方法来短路许多返回布尔值的连续方法。
Ex见下面的例子。可以使用lambdas进行流式传输或实现吗?
public boolean outerMethod() {
if(booleanMethod1() && booleanMethod2() && booleanMethod3() && ...) {
// Do work
} else {
// Do something else
}
}
如果我的condition1 && condition2 && ... && conditionN
列表增长太长,我最喜欢的重构通常是
boolean theMeaningOfANDingAllConditions = condition1
&& condition2
&& ...
&& conditionN;
if (theMeaningOfANDingAllConditions) {
// Do work
} else {
// Do something else
}
我不认为“短路”是你正在寻找的词。那有a specific meaning。
如果你想要做的是将你的条件组合成一个较短的行,将它们组合成一个函数是一种常见的模式。
if (allBooleanMethods()) {
// Do work
} else {
// Do something else
}
...
private boolean allBooleanMethods() {
boolean result = booleanMethod1();
result = result && booleanMethod2();
result = result && booleanMethod3();
return result;
}
当然,你可以用流实现它:
boolean result = Stream.<Supplier<Boolean>>of(
() -> a(),
() -> b(),
() -> c()
)
.allMatch(Supplier::get);
但问题确实是它会让它更优雅。我不这么认为。
我会坚持使用&&
:
boolean result =
aMethodName() &&
anotherMethodName() &&
yetAnotherMethodName() &&
moreOfThem...
if (result) {
...
}
else {
....
}