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
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.
I asked it on stackoverflow: https://stackoverflow.com/questions/54113639/how-to-properly-implement-this-using-vavr
:)
Most helpful comment
I asked it on stackoverflow: https://stackoverflow.com/questions/54113639/how-to-properly-implement-this-using-vavr
:)