Null Pattern
Last time I blogged about “Learn the Null Pattern“, but I forgot to mention one thing about the Null Pattern. That is you have to be mindful of it.
For example
foreach(var id in IDList)
{
var employee = db.GetEmployee(id);
salary = db.CalculateSalary(id);
employee.Pay(salary);
}
The code looks okay but what if the GetEmployee method actually returns a NullEmployee? Well that would still be okay, since when the Pay method is called it would just do nothing.
Now what if we did this though
var numberOfEmpolyeeWhoGotPaid = 0;
foreach(var id in IDList)
{
var employee = db.GetEmployee(id);
salary = db.CalculateSalary(id);
employee.Pay(salary);
numberOfEmpolyeeWhoGotPaid++;
}
Now we get into trouble since we counted even the Null Employee.
Again be mindful of Null Object Pattern when you use it, since it may cause you headache in the future of finding that nasty bug, but nevertheless the Null Object Pattern is still a very useful pattern under your belt.