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
1 2 3 4 5 6 |
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
1 2 3 4 5 6 7 8 |
var numberOfEmpolyeeWhoGotPaid = 0; foreach(var id in IDList) { var employee = db.GetEmployee(id); salary = db.CalculateSalary(id); employee.Pay(salary); numberOfEmpolyeeWhoGotPaid++; } |
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.
Leave A Comment