在满足要求之前有条件地调用多个方法的最佳方式



我有一系列方法,我想连续调用它们,直到其中一个返回有效值,然后跳过其余的

String value = ""; //invalid value
while (true) {
value = someMethod.getValue();
if (value.length() > 0) break;
value = someOtherMethod.getValue();
if (value.length() > 0) break;
value = yetAnotherMethod.getValue();
break;
}

它工作得很好,但我不喜欢创建一个无限循环然后手动打破它的概念。有更优雅的方法吗?

没有(IMO(优雅的方式。但是有比你写的更简单的方法。例如:

String value = someMethod.getValue();
if (value.length() == 0) {
value = someOtherMethod.getValue();
}
if (value.length() == 0) {
value = yetAnotherMethod.getValue();
}

在某些情况下,对于问题的某些变体,您可能能够使用循环和Lambda数组、流或类似的方法来制定解决方案。然而,这将涉及开销和样板(以及读者的挠头(。。。在我看来,这并不优雅。

我认为Optional class是显示"如果这是不好的,那么采取"-意图

Predicate<String> isNotEmpty = word -> word.length() > 0;
value = Optional.of(someMethod.getValue())
.filter(isNotEmpty)
.or(Optional.of(someOtherMethod.getValue())
.filter(isNotEmpty)
.orElse(yetAnotherMethod.getValue());

如果someMethod.getValue()someOtherMethod.getValue()方法在没有值的情况下返回Optionals来表示,这看起来要好得多。

value = someMethod.getValue()
.or(someOtherMethod.getValue())
.orElse(yetAnotherMethod.getValue());

最新更新