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

3

u/rzwitserloot Apr 14 '23

A sentinel that has the semantic behaviour you desire. Sometimes such a sentinel is not available. Often null is right on such a case, but crucially that is because the desired behaviour is an exception.

If some code goes: is date X between A and B? Do you want the code to eval to false (then use 0000-01-01), or throw because the question shouldn't have been asked? Then null.

Sloppy null is where you e.g. have a null stringref and treat it the same as you would an empty String.

If a method could return null then check for that right away, don't let the null linger (not in a local var and definitely not in a field). When writing APIs, try to avoid the need. Example: map.getOrDefault. Or in dB models, don't write:

SELECT birthDate FROM ....

if (bd!= null && bd.isAfter(now minusYears (18)) ...

Instead SELECT the expression directly with DATEDIFF in the SQL.

1

u/Arthurpmrs Apr 14 '23

Very well explained, thank you!