I have A string and B string , app prefers A if not null, and call transformation method changeA(). However if A is null , it will use B and invoke method changeB() . Both transformation method return same object type Result. However one thing to note is that str B might null too, then if that case return null instead.
How do I approach this using optional and lambda expression in JDK.
I have the following codebase:
changeA(){
..
}
changeB(){
..
}
aMethod(){
Optional<String> optA=Optional.ofNullable(a);
Result result = optA.map( aStr -> this.changeA( aStr ) ).orElse( this.changeB( bStr ) );
}
This looks a bit weird cause the orElse method is using variable not within the scope of the lambda. May I know the best approach to this ?
Perhaps I should state why I chose Optional. I want my team's developer to understand that even though String A is preferred , it might be null and must be handled since the part of the code is sensitive . String B is used for legacy part of the records only. Hopefully this clarify my intention on this approach.
filterstep... I think the best approach is good oldif-elseor?::) - ZhongYuOptionalis as a return value. That way developers are forced to handle the possible absence of a value, which should prevent NPEs. You, on the other hand, not only know thatacan be null, but also have a method whose sole purpose is to handle that situation. Using anOptionalhere is somewhat pointless. - a better oliver