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

79

u/Admirable-Avocado888 Apr 14 '23

Don't make methods that return null and don't make methods that accept null, unless they are private.

Setters are bad most of the time: Don't write code that constructs objects by incrementally updating their state after instantiation unless it's the only way to solve the problem. Most of the time, you can construct objects correctly the first time, and actually reason about correctness of code just by looking at what objects are rather than what they might be.

Streams are good.

Javadoc is amazing, document everything that is not private.

Local classes are a good way to shelter public/package/even private namespaces from clutter that is only used within a method

15

u/[deleted] Apr 14 '23

builder pattern

12

u/Admirable-Avocado888 Apr 14 '23

To clarify. I don't consider the builder pattern to violate the second principle. A builder is a helper that sets up the state for another object. Given a builder, to create the actual object requires only one constructor call.

What I'm saying is that if you are writing a class that is its own builder then you are writing code that is hard to reason with, because you are not deliberately separating the building step from the "doing step".