java - Is there a convention that objects created using the Builder pattern be immutable? -


according book design patterns: elements of reusable object-oriented software,:

the builder pattern separates construction of complex object representation same construction process can create different representations.

in general builder pattern solves issue large number of optional parameters , inconsistent state providing way build object step-by-step , provide method return final object.

with builder pattern go have build method generate object witch immutable.

my question:

can use builder pattern keeping setters methods in class of generate object, allowing possibility mutate built object ?

if go produce mutable objects, shouldn't use builder pattern ?

there value in builder pattern goes beyond helping solve telescoping parameter problem.

  • they can make api easier use clients since setter methods self-naming and, therefore, easier remember.
  • the builder pattern enables optional parameters, offered telescoping constructors using potentially awkward overloading.
  • client code uses builders can more self-documenting code uses constructors, enabling client code easier (and cheaper) maintain
  • the builder pattern can reduce bugs. large lists of identically typed parameters can accidentally transposed telescoping constructors. in such case, compiler won't report error , resulting bugs can far removed , hard track down.
  • mandatory parameters objects can specified in constructor signature builder. compiler insist these mandatory parameters provided @ compile time.
  • useful apis evolve on time; easy add setter methods builder object, while can less easy , more error-prone manage set of overloaded constructors.
  • the builder pattern concurrency friendly. relatively straightforward keep mutable builder object thread confined and, therefore, threadsafe.

builders useful constructing immutable objects because, such objects, data must supplied @ build time. when there large amount of data supply or when multiple steps must completed, builder pattern pretty easy recommend.

there no rule builder objects can't build mutable objects, mutable objects javabeans pattern provides same benefits (easy readability, self-documentation, reduced error prone-ness) less code.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -