このコードを機能的な方法で適切に記述する方法について、アドバイスをお願いします。
private Option<CalcResult> calculate(Integer X, Integer Y) {
if (X < Y) return Option.none();
return Option.of( X + Y );
}
public Option<CalcResult> otherMethod(Obj o) {
if (o.getAttr()) {
// getA() & getB() are APIs out of my control and could return a null value
if (o.getA() != null && o.getB() != null) {
return calculate(o.getA(), o.getB());
}
}
return Option.none();
}
計算は簡単です:
private Option<CalcResult> calculate(Integer X, Integer Y) {
return Option.when(X > Y, () -> X + Y);
}
の場合otherMethod
、これが私の最初のアプローチでした:
public Option<CalcResult> otherMethod(Obj o) {
return Option.when(o.getAttr(), () ->
For(Option.of(o.getA()), Option.of(o.getB()))
.yield(this::calculate)
.toOption()
.flatMap(Function.identity())
).flatMap(Function.identity());
}
しかし、最初のバージョンと比較して、コードが思ったほど読みにくくなっていると感じます (doubleflatMap
を使用すると、一目でわかりにくくなります。なぜそこにあるのか)。
私はこの他のものを試しました。これにより、講義が改善されます。
public Option<CalcResult> otherMethod(Obj o) {
return For(
Option.when(o.getAttr(), o::getAttr()),
Option.of(o.getA()),
Option.of(o.getB()))
.yield((__, x, y) -> this.calculate(x, y))
.toOption()
.flatMap(Function.identity());
}
はるかに読みやすいですが、この場合、For 内包表記を正しく使用していないと思います。
この場合のおすすめは?vavr の API を正しく使用していますか?
ありがとう