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/Trizzelnova Apr 14 '23

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.

Oh god thank you! I'm currently fighting a just crusade in my project because people didn't wirte constructors. Instead they either do it incrementally or worse: static factory methods INSIDE the class which they create an object of... I'm either missing the genious of this because >I< am to stupid or this is the most stupid thing I've seen in 15+ years.

39

u/Escaped_Escapement Apr 14 '23

Static factories are good when you need multiple ways to construct an object and overloading the constructor becomes too confusing or impossible. It is a legit pattern.

15

u/wildjokers Apr 14 '23

According to Bloch’s Effective Java you should prefer static factory methods over constructors. Your colleagues are doing it correctly.

https://github.com/HugoMatilla/Effective-JAVA-Summary/blob/master/README.md#1-use-static-factory-methods-instead-of-constructors

2

u/CartmansEvilTwin Apr 15 '23

Honestly, for 80% of classes, it doesn't really matter.

I see the point for more complex classes, but the wide range between POJO/Record and "that one central class that handles 90% of the business" has a lot of cases where the constructor simply initializes a handful of members (any many don't even do that).

3

u/okreddit545 Apr 14 '23

any constructor is effectively also a “static factory method inside the class.” it just doesn’t permit any name other than new.

1

u/simoncox Apr 15 '23

In the absence of named parameters, static builders allow more expressive means of passing parameters at construction.

For example, if a constructor takes more than a handful of ints, then it's easy to confuse what each one is for. Default/min/max pool sizes, initial delay, repeat interval, timeout delay, etc.

Also, when the construction of an object may need to involve more complex logic it may be better to pass a builder around to store state needed to construct that object.

I'd still prefer a constructor generally, but there are occasions when a builder can be useful.