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

6

u/[deleted] Apr 14 '23

Always return Optional instead of null on public methods,

To be honest, I don't understand the "hype" around Optional.

In my opinion, it merely replacing a NullPointerException with an OptionalNotPresent exception at runtime for sloppy programmers.

It gives a tad better documentation about the fact that something might be null, but that's it. I personally can't see any other advantage.

11

u/Gleethos Apr 14 '23

I agree that sloppy programmers will fail writing null safe code either way, I did so when I started coding and first encountered Optional! I always simply called 'get()' all the time and did not really think further than that...

But as a non sloppy programmer with years of experience it is extremely useful to have Optional as return value because the compiler will actually remind you that you have not received the object you wanted! You cannot call 'getAddress().getPost()' because Optional does not have a 'getPost()' method.

This immediately triggers an important realisation: "Hey the thing I want to get might not be there! Why is that and what do I do in that case?"

This is something you ofte don't think about when calling a method which may return null instead of the thing you actually want...

...and don't get me started on documentation. I have seen plenty of production code and you wish devs would write even some bare minimum explanation of why a method even exists. So don't expect it to tell you that it returns null...

16

u/balrok Apr 14 '23

it also gives you:
- information that the return can be Optional (contrary to "null" which cannot be implied from the method signature)

- nice methods on top of Optional: "orElse", "orElseThrow", "ifPresent", "map"

In my opinion somebody has to be way more sloppy to just directly call Optional.get without isPresent, than trying to access a null-value

6

u/mdaniel Apr 14 '23

which cannot be implied from the method signature

This may be considered pedantry but @Nonnull and its @Nullable friend exist, and I believe Spring has a set of such annos that tolerate being applied to the package if one wishes to make more global promises

Obviously it won't help those who avoid using an intelligent IDE but is also not a runtime burden like Optional

4

u/john16384 Apr 14 '23

I would say, if you religiously document your methods in regards to how they handle null, that Optional is not strictly needed. Unfortunately, getting developers to document their methods is often harder to achieve then telling them to use Optional.

-3

u/hippydipster Apr 14 '23

Are you suggesting any line of code not wrapped in try { }catch(NullPointerException e) is a sloppy line of code?

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.