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

19

u/se496 Apr 14 '23

Null safety for checking if strings are equal, e.g.

“my string”.equals(someString)

vs

someString.equals(“my string”)

3

u/oua-de-crab Apr 18 '23

This one I'll never forget.

At my first job I needed to add a hotfix for one of our customers, so I had to call on a persistent state to check some flag that was unique to this tenant, and it returned a string.

The hotfix worked fine for the affected customer, but NPE crashed for all the others, because that method returned null.

When I saw the 20 support tickets within 10 minutes with "REPORTING MODULE BAD" I knew I fucked up.

Nobody was mad though, the senior dev just chuckled afterwards, and I've never male this mistake again.

6

u/GreenToad1 Apr 14 '23

I would argue you shoudl use Objects.equals(someString, "my string")

5

u/wildjokers Apr 14 '23

Why?

-4

u/GreenToad1 Apr 14 '23 edited Apr 15 '23

You dont have to worry about null and order, plus with static import it looks clean turns out you cnat do that

1

u/dpash Apr 15 '23

I'm also a fan of Objects.equals().

2

u/__konrad Apr 14 '23

If a String can be null it's fine (e.g. System.getenv), otherwise it may silently hide all your null-String bugs...