Thursday, December 25, 2008 10:58 AM
kolbis
Design Decision: Null Objects
Have you ever seen this code:
class Program
{
static void Main(string[] args)
{
Person p = new PersonManager().GetPersonById(1);
}
}
class PersonManager
{
public List<Person> People { get; set; }
public PersonManager()
{
People = new List<Person>();
}
public Person GetPersonById(int id)
{
Person res = (from p in People
where p.Id == id
select p).FirstOrDefault();
return res;
}
}
class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
Take a look at the GetPersonById method within the PersonManager class. What will be the outcome?
That is right, it can be either NULL or the person object that we found in the list. Now, do not get me wrong, it is not that there is something wrong with this code...It is the fact that we have a design decision to make regarding it that we usually ignore.
The Problem
So, what is the design decision we need to make? As the post title implies, I mean that we need to decide whether objects returned from methods can return as NULL. We have three options when returning objects from a method:
- The actual value - on success.
- NULL - on failure.
- Empty object - on failure.
Option number 2 and 3 are a result of failure to execute the method. In my example, it indicates that the Person was not found in the list.
Now, because we have two options we can select when to use the NULL and when to use the Empty object. This allows each developer to do what he feels like. This can lead to inconsistency in the code. This can lead to bugs...and believe me, there will be bugs.
The Solution
We must make a decision. We need to create a standardization to this issue. I like calling it "NULL Object" decision. Every developer should use the same standard for returning objects from methods. It can be either of the above. Both is fine! But make sure you follow it always.
How To Decide?
I like my team to help me decide, so I usually gather my team together and hold a discussion. At the end of it, we vote. The result will be our decision. The best time to have this meeting is at the beginning of the development. However, if you are using an Agile methodology, the next iteration is a good candidate.
תגים:Software Development, Architecture, Dev