What I am trying to achieve:
Use Java Optional to refactor null check.
Background:
I have a straightforward POJO class:
public record MyPojo(String someField, String someOtherField)
And this method:
private static String question(final MyPojo mypojo) {
if (null == mypojo) {
return null;
} else if (null == mypojo.someField()) {
return null;
} else {
return mypojo.someField().toLowerCase();
}
}
Issue:
As you can see, while super easy to understand, this code is very verbose and lengthy.
MyPojo can be bull, and so can MyPojo.someField.
I need to check those two preconditions before applying my business logic (here lower case just for example)
Question:
Is there a smarter way, either using Optional, or something smarter, to refactor this?
>Solution :
You can chain your optional with .map() calls, the advantage of this approach is that it chains the operations together in a readable way and eliminates the need for explicit null checks:
private static String question(final MyPojo mypojo) {
return Optional.ofNullable(mypojo)
.map(MyPojo::someField)
.map(String::toLowerCase)
.orElse(null);
}