Vavr: How to properly implement this?

Created on 6 Jan 2019  路  3Comments  路  Source: vavr-io/vavr

Hello,

I would like got your advise on how to properly write this code on a functional way:

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

Calculate is simple:

private Option<CalcResult> calculate(Integer X, Integer Y) {
  return Option.when(X > Y, () -> X + Y);
} 

For otherMethod, This was my first approach:

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

But, I feel the code is not as readable as I would expect, compared to first version (double flatMap makes hard to understand, at first sight, why is there)

I tried with this other, which improves the lecture:

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

It's way more readable, but I think i'm not correctly using For-comprehension on this case.

What would be your recommendation on this case? am I correctly using vavr's API?

Thanks

question

Most helpful comment

All 3 comments

Please ask the question in our Gitter chat! We can't answer general questions here.
(You may reference this issue in order to save some keystrokes...)
Thx!

Chat is ephemeral, so if you think your question might benefit others too, consider posting it on stackoverflow.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jniedzwiecki picture jniedzwiecki  路  6Comments

Vivek-Patil picture Vivek-Patil  路  3Comments

Pyeroh picture Pyeroh  路  3Comments

carnott-snap picture carnott-snap  路  4Comments

liviamoroianu picture liviamoroianu  路  3Comments