개인공부/language

[JAVA] Effective JAVA - Item 2 : Consider a builder when faced with many constructor parameters

파뱁 2025. 3. 7. 16:08
728x90

Case : scale well to large numbers of optional parameters

-> static factories and contructors not good for this case

 

then how to solve this case?

 

The answer is : Builder

 

Traditionally programmers have used the 'telescoping constructor'

but, there have some problem

  •  Hard to write client code
  • Harder to read it

 

and also you can say 'how about use JavaBeans'

but there are still have some issues.

  • Inconsistent state partway through its construction
  • Precludes the possibility of making as class immutable

 

Luckily, there is the 'Builder pattern'

 

Let's see how it works

  1. Client calls a constructor with all of the required parameters and gets a builder object
  2. Client calls setter-like methods on the builder object to set each optional parameter of interest
  3. The client calls a parameterless build method to generate the object, which typically immutable

Advantages of Builder pattern

  • Simulates named optional parameters
  • Well suited to class hierarchies

Summary

The builder pattern is a good choice when designing classes whose constructors or static factories would have more then a handful of parameters
728x90
반응형