1

我想就如何以功能方式正确编写此代码获得您的建议:

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()); 
}

它更具可读性,但我认为我在这种情况下没有正确使用 For-comprehension。

您对此案有何建议?我是否正确使用 vavr 的 API?

谢谢

4

1 回答 1

1

我会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())
      ));
}

我在你的例子中替换CalcResult为因为,真的返回一个,我让你适应你的商业模式。IntegercalculateOption<Integer>

于 2019-01-14T23:00:15.607 回答