I have finally come to the conclusion that no object should
be allowed to be constructed in any way that will allow for the object to be setup in an
Way too often I see an object that uses the empty constructor
which then requires the user to ‘guess’ which properties are needed to setup
the object correctly. This in my opinion
just leads to poor code and really hard to find bugs. I would suggest that if an object needs certain
values to be considered ‘valid’ then these values need to be provided during
Imagine if you will you have an object; let’s call it the ‘Manager
Object’. In order for this object to be
valid you need to provide it with the ‘ID’, ‘Name’ and ‘Authority Level’. If you have an empty constructor, the users
of the object must KNOW those values are needed. If they don’t provide them very odd/subtle
bugs may appear.
Now if your object’s constructor (or builder, factory, what
ever) required those values at construction time no one would be able to build
the object in an invalid state. You
could even go as far as asserting the values passed in to make sure they are
within valid ranges.
By requiring your objects to be constructed in valid state at
all times you will have more confidence in your app as well as a cleaner code
base. Oh, and by the way, the I would
also suggest that the properties are read-only UNLESS EXPLICITLY needed for
setting, this will also enforce a more stable object.
Finally, I know this seems way too obvious to many as simply best practice. However just because it is obvious does not mean it is followed...... :(
05-04-2007 6:29 AM