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 fully populated? 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 “Set” 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.

If you don’t like writing “normal” constructors them make them static and call them Create or something obvious.

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

I have noticed that it is hard to make lists in the GUI 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.

Tags: , ,

Leave a Reply