I had a discussion with some work colleges a short while ago,
around a couple of different techniques of constructing a class object.
The two approaches involved in the discussion where…
- Should we prefer constructing an object by providing public access to its members and initialising them external to the class, like the Builder pattern does?
- Or by initialising the objects members within its constructor, I.E. like the Factory Method and Abstract Factory does?
My take on this, was that it would be best object oriented practice to keep the initialisation of the objects members within the constructor if possible.
As far as I’m aware, there seems to be more support for the “keeping initialisation within the constructor”.
Some of my supporting arguments were the following
From Steve McConnell’s Code Complete
Chapter 6: Working Classes
Initialise all member data in all constructors, if possible.
Initialising all data members in all constructors is an inexpensive defensive programming practice.
Chapter 10: General Issues in Using Variables
Initialise a class’s member data in its constructor.
Just as a routine’s variables should be initialised within each routine, a class’s data should be initialised within its constructor.
Builder pattern verses the likes of the Factory Method and Abstract Factory.
Notice the Frequency of use for the Builder verses the other two?
Examples of class’s that know how to populate themselves
You can get code examples here if you’re not familiar with the patterns.
Any feedback on what people think about the before mentioned approaches would be great.