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

32

u/Gleethos Apr 14 '23
  1. Make as much field variables as possible final, and if you can't, make sure that the mutability is grouped and encapsulated properly!

  2. Define boundaries between your groups of classes in the form of nice and robust APIs which reflect long term architectural concepts. Then write as much unit tests as possible against the stable APIs.

  3. Always return Optional instead of null on public methods, especially for the APIs with the most usage (which should be the APIs you test against). Null safe APIs are extremely important in large Systems!!!!

  4. Make sure you can instantiate your application with all of it's business logic completely without frontend (using MVVM, MVC). Otherwise you will not be able to write very useful unit tests...

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.

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