Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use Java Optional to refactor null check

What I am trying to achieve:

Use Java Optional to refactor null check.

Background:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading