我想得到你关于如何以功能性方式正确编写此代码的建议:
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());
}
但是,与第一个版本相比,我觉得代码并不像我预期的那么可读(乍一看,双flatMap
很难理解,为什么会有)
我尝试了另一个,这改善了讲座:
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());
}
它更具可读性,但我认为在这种情况下我没有正确使用理解。
你对这个案例有什么建议?我是否正确使用了vavr的API?
谢谢
我会完全按照你的方式编写calculate
(除了我永远不会对参数使用大写:P)。
至于otherMethod
,我会使用模式匹配。Vavr 中的模式匹配甚至不接近 Haskell 等函数式语言中的 PM,但我认为它仍然正确地代表了您的意图:
public Option<Integer> otherMethod(Obj o) {
return Option.when(o.getAttr(), () -> Tuple(Option(o.getA()), Option(o.getB()))) //Option<Tuple2<Option<Integer>, Option<Integer>>>
.flatMap(ab -> Match(ab).option( // ab is a Tuple2<Option<Integer>, Option<Integer>>
Case($Tuple2($Some($()), $Some($())), () -> calculate(o.getA(), o.getB())) // Read this as "If the pair (A, B)" has the shape of 2 non-empty options, then calculate with what's inside
// Result of Match().option() is a Option<Option<Integer>>
).flatMap(identity())); // Option<Integer>
}
替代,没有注释(注意我们使用Match().of()
而不是Match().option()
,所以我们必须处理所有可能的形状):
public Option<Integer> otherMethod(Obj o) {
return Option.when(o.getAttr(), () -> Tuple(Option(o.getA()), Option(o.getB())))
.flatMap(ab -> Match(ab).of(
Case($Tuple2($Some($()), $Some($())), () -> calculate(o.getA(), o.getB())),
Case($(), () -> None())
));
}
我用Integer
替换了CalcResult
,因为在您的示例中,calculate
真正返回Option<Integer>
,我让您适应您的业务模型。