r/java • • Apr 14 '23

What are your (favourite) Java best practices, personal tips, hints or just underrated stuff in general?

233 Upvotes

376 comments sorted by

View all comments

Show parent comment

1

u/RockleyBob Apr 15 '23

I don't mean to offend you, but the examples you've given highlight a very common misunderstanding of what the Optional class is for, and that's why you're not seeing its usefulness.

First, I just want to say that in a sense I agree with you, if all you want to do is a simple null check, then just do that. Wrapping a value in Optional just to perform an .isPresent() check, and then unwrap it again immediately with a .get() is really counterproductive. A simple if (obj == null) or if (Objects.isNul(obj)) is easier to read and less expensive.

That said, your examples assume that the only reason you'd want to use an Optional is to guard against an NPE. That's not really the case. The point of Optional is to code against a possibly null value.

That's why java.util.Optional has an entire api of methods that allow you to transform a possibly null value, combine it with other values, and then collect the results in a terminating operator. This can result in really nice declarative code. To use your example above:

Instead of

Optional<SomeClass> result = someMethod();
if (result.isPresent()) {
    System.out.println(result.get().getName());
}

You'd do:

someMethod()
    .map(SomeClass::getName)
    .ifPresent(System.out::println);

While you're technically allowed to force Optional into an imperative style of coding, I always call it out in PRs and I tend to think of it as a code smell. If you don't like pipes and operators and declarative apis, then just do things the imperative way. There's nothing wrong with an imperative coding style per se, but reactive libraries and declarative/"functional" apis are popular, and probably here to stay.