martinfowler.com logo Home Blog Articles Books About Me Contact Me ThoughtWorks

SetterInitialization design Reactions

One of two approaches to initializing objects, the other is ConstructorInitialization.

With setter initialization you construct an empty object and then use setter methods to setup various properties as you go. So create a person with firstname, lastname, and a collection of favorite bars we might see something like

#ruby
mf = Person.new
mf.firstname = 'Martin'
mf.lastname = 'Fowler'
mf.add_bar "Turner's Oyster Bar"
mf.add_bar "Square and Compass"

This approach gives you the maximum flexibility in wiring up objects, allowing you to provide just the collaborators you need for a specific usage.

It frees you from having to set all the values at once - which is handy if some objects are only available at later times.

Each method call is compact, which avoids the problem of long parameter lists to constructors and an array of different constructors to choose from.

Marko Schulz reminded me that setter methods have names that explain their use for the new object - this is a noticeable advantage over ConstructorInitialization in most languages these days which only have positional parameters. Constructor parameters with very general types (strings etc) can easily get very cryptic.


Links
home
bliki
feed 
Translations
Japanese
Spanish
Korean
Chinese
Thai
Categories
agile
design
dsl
leisure
refactoring
ruby
thoughtWorks
tools
uml
writing
Blog Roll
ThoughtBlogs
TW Alumni
Nicholas Carr
Steve Cook
Brian Foote
Simon Harris
Gregor Hohpe
/\ndy Hunt
Ralph Johnson
Patrick Logan
David Ing
Brian Marick
Jeremy Miller
Jimmy Nilsson
Samuel Pepys
Keith Ray
Johanna Rothman
Kathy Sierra
Dave Thomas

martinfowler.com logo mingle logo thoughtworks logo

© Copyright Martin Fowler, all rights reserved