[Effective Java] [Item 2] Consider a builder when faced with many constructor parameters

Опубликовано: 29 Октябрь 2024
на канале: Omkar Shetkar
2,344
25

Telescoping constructor pattern - does not scale well!
unreadable, prone to hard to debug errors

JavaBeans pattern - allows inconsistency, mandates mutability
invariance cannot be maintained
maintaining thread safety of the class difficult

Builder pattern - safe and readable
Parameter validation can be done while object construction
Can have multiple varargs parameters
Builder pattern is flexible
Builder whose parameters have been set makes a fine Abstract Factory

Disadvantages
Creating a builder object may be costly in some performance critical situations
It is more verbose than telescoping constructor pattern

Summary
Builder pattern is a good choice when designing classes whose constructors
or static factories would have more than a handful of parameters