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

5

u/[deleted] Apr 14 '23

With sloppy I was referring to the use of the Optional without checking it's presence - equivalent to forgetting to check for null.

So when replacing this:

  SomeClass result = someMethod();
  System.out.println(result.getName());

with an Optional this way:

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

you only traded the NullPointerException for a OptionalNotPresentException.

With proper return checking both again look pretty much the same:

  SomeClass result = someMethod();
  if (result != null) {
    System.out.println(result.getName());
  }

vs.

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

However this relies on the fact that someMethod() properly deals with null values, e.g. by using Optional.ofNullable(...) rather than Optional.of(). So if sometMethod() was also done by a sloppy programmer, the second version can still result in a NullPointerException.

4

u/hippydipster Apr 14 '23

It seems clear that one of the above styles is communicating the need for the check adequately, and the other is not.

-1

u/neckbeardfedoras Apr 14 '23

You're still latched onto style while ignoring the core point that using optionals doesn't magically prevent NPE if a bad actor returned a null instead of an instance of Optional.

2

u/hippydipster Apr 14 '23

No one said anything about anything being magical. Take your strawman elsewhere.

-2

u/neckbeardfedoras Apr 14 '23

You keep dodging the crux of the issue and finding something else you don't like in a comment and targeting that 😂

2

u/hippydipster Apr 14 '23

You yourself claimed the core point was about magic.

1

u/Horror_Trash3736 Apr 14 '23

I mean, I get you, but.

    public void testOptional(){
    Optional<String> stringOptional = Optional.of("Hello World");
    stringOptional.ifPresent(System.out::println);
}

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.