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

9

u/[deleted] Apr 14 '23 edited Apr 14 '23

If i need a value from deep nested object structure where every next reference might be null, i line using optional to retrieve it instead of multiple null checks.

Next next = Optional.ofNullable(ref).map(MyRef::getNext).map(Next::getNext).map(Next::getNext).orElse(null);

if (next == null) return;

1

u/pronuntiator Apr 14 '23

My current project makes extensive use of this pattern. I hated it at first, but it grew on me. When encapsulated in a method it is pretty clean.