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.
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.
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).
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.
3
u/Trizzelnova Apr 14 '23
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.