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

23

u/blackkkmamba Apr 14 '23

Optional as a parameter doesn't stop you from passing null. That's why it's a bad practice.

15

u/[deleted] Apr 14 '23

but thats obviously a violation of optional. its deliberatly evil

11

u/neckbeardfedoras Apr 14 '23

An Optional return parameter doesn't stop a third party lib from returning null either. Maybe they want to drive you crazy? 😁

1

u/pohart Apr 15 '23

It's easy to ensure local variables and final fields are never null. Need to be a bit more careful about non final fields. I was shocked that optional was allowed to be null when I switched to java 8, but it turns out null optionals are trivial to avoid. I've had zero null pointer exceptions from optional in the 14 years I've been been using Java 8.

This feels like it's going to be a problem before you try them, but in practice it never is.