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.
GOF
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.
Tags: Architecture, Design Patterns
October 15, 2010 at 20:15 |
I have a discussion going on at the stack.
http://stackoverflow.com/questions/3898629/class-construction-techniques
November 5, 2010 at 09:00 |
Thank you for share very good info. Your web is greatI am impressed by the information that you have on this blog. It shows how well you understand this subject. Bookmarked this page, will come back for more. You, my friend, ROCK! I found just the information I already searched everywhere and just couldn’t find. What a perfect site. Like this website your website is one of my new favs.I like this info presented and it has given me some sort of desire to have success for some reason, so thank you
July 10, 2014 at 00:58 |
My spouse and I stumbled over here by a different web address
and thought I might check things out. I like what I see so
now i am following you. Look forward to looking at your web page repeatedly.