2008-06-18

Make sure your objects are fully populated – Fail At Once

The default constructor
public Customer()
{
}

is seldom needed while working with business objects. Honestly – how do you need an object that is not? Do you have a Customer or do you not? A few situations comes to mind where an almost-Customer is needed but they all smell of refactoring, i.e. base class, sub class and two constructors.

To make sure I don't have an object that is not fully populated I make sure the default constructor is not reachable. Either through creating other constructors or by making it private the times it is needed internally. Instead I create a constructor that takes all necessary parameters to fully populate itself. If there are variants I create more constructors. I am not afraid of writing code but I strongly dislike putting bugs into production. Hence Fail At Once.

Sometimes it is handy to have a void method taking all parameters and calling it from the constructor but this is just a variant of the pattern above that objects that are not correctly populated are very seldom useful.

Another advantage with this routine is when adding (or removing) another mandatory field. Then there is one and only one place to update to make the compiler give you all places to update.

I have noticed that it is hard to make handy lists without having a default constructor but this, I presume, is just the exception that confirms the rule.

Bugs that can't compile will not go into production.

No comments: