JAJAH Development Blog

Blogs by JAJAH Developers

Archive for the ‘patterns’ Category

Monday, December 10th, 2007

There is a lot written about the null object pattern in the web, but it took me quite some time to find an example that I could relate to for null object.

Take a scenario where we have a email application with a message class:

public class Message
{
    private string m_recipient;
    private MailAccount m_account;

    public string Recipient
    {
        get { return m_recipient; }
        set { m_recipient = value; }
    }

    public MailAccount Account
    {
        get { return m_account; }
        set { m_account = value; }
    }
}

Lets say that we would like to view the massage pane window (pretty common requirement for a mail client), we will have to test the the Recipient and Account member for null value before accessing them.

Side effects when testing for null values is that we add code to the presentation logic which can possibly look like that:

void ShowMessage(Message m)
{
    string recipientDisplay = m.Recipient ?? String.Empty;

    string accountDisplay = m.Account ?? "NotSet";
    if(m.Account == null)
    {
        accountDisplay = "NotSet";
    }
    else
    {
        accountDisplay = m.Account.Name;
    }
    txtRecipient = recipientDisplay;
    txtAccountName = accountDisplay;
}

This is a lot of code just for displaying two fields. We should also remember that a developer can possibly forget to test for null values and therefore to get a null reference exception.

The null object attempts to help here. One possible implementation is by implementing the Message class like this:

public class Message
{
    // String.Empty is the null object for recipient
    private string m_recipient = String.Empty;

    // Set the "NotSet" account as the default value
    private MailAccount m_account = MailAccount.NotSet;

    public string Recipient
    {
        get { return m_recipient; }
        set { m_recipient = value; }
    }

    public MailAccount Account
    {
        get { return m_account; }
        set { m_account = value; }
    }
}

Where the MailAccount class is implemented like that:

public class MailAccount
{
    public static readonly MailAccount NotSet =
        new MailAccount("Not set", "0.0.0.0", false);

    private string m_name;
    private string m_serverAddress;
    private bool m_isSsl;

    public MailAccount(
        string name, string serverAddress, bool isSsl)
    {
        //parameter validation…
        m_name = name;
        m_serverAddress = serverAddress;
        m_isSsl = isSsl;
    }

    public string Name
    {
        get { return m_name; }
    }

    public string ServerAddress
    {
        get { return m_serverAddress; }
    }

    public bool IsSsl
    {
        get { return m_isSsl; }
    }
}

Here you can see that there is a static property called NotSet which is the null object. The field m_account is set by default to the NotSet account. The field m_recipient is set to String.Empty which also serves as a null object.

void ShowMessage(Message m)
{
    txtRecipient = m.Recipient;
    txtAccountName = m.Account.Name;
}

Because we know that both Recipient and Account are not initialized to null, we can skip the null checking and thus we get much simpler and more readable code.

One thing that I like, is that now when the account is a null object (account not set), the default values will be displayed ("Not set" and address "0.0.0.0").

A small problem with this kind of implementation is that the properties of the NotSet instance can be changed by reflection but the next part can solve that.

Another way to implement a null object is by subclassing or implementing an base interface. Based on the previous example, lets add an interface that represents an account:

public interface IMailAccount
{
    bool IsSsl { get; }
    string Name { get; }
    string ServerAddress { get; }
}

The MailAccount class will now look like that:

public class MailAccount : IMailAccount
{
    private string m_name;
    private string m_serverAddress;
    private bool m_isSsl;

    public MailAccount
        (string name, string serverAddress, bool isSsl)
    {
        //parameter validation…
        m_name = name;
        m_serverAddress = serverAddress;
        m_isSsl = isSsl;
    }

    public string Name
    {
        get { return m_name; }
    }

    public string ServerAddress
    {
        get { return m_serverAddress; }
    }

    public bool IsSsl
    {
        get { return m_isSsl; }
    }
}

Pay attention that the class now implements the IMailAccount interface and it does not contain the null object static field. The null object is implemented like this:

public class NullMailAccount : IMailAccount
{
    public NullMailAccount() {}

    public bool IsSsl
    {
        get { return false; }
    }

    public string Name
    {
        get { return "NotSet"; }
    }

    public string ServerAddress
    {
        get { return "0.0.0.0"; }
    }
}

and then the Message class will look like like this:

public class Message
{
    private static readonly IMailAccount
        MailAccountNullObject = new NullMailAccount();

    // String.Empty is the null object for recipient
    private string m_recipient = String.Empty;

    // Set the mail account null object
    private IMailAccount m_account = MailAccountNullObject;
    …

The usage of the Message class remains the same.

This implementation is also safe for reflection since the NullMailAccount class has no fields to change and in the class message, the field MailAccountNullObject is a readonly field which can’t be set by reflection.

So to conclude, the points that I liked the most about the null object pattern are:

1) Reduces significantly the chances of getting a null reference exception.

2) Defines a common behavior for fields that were not set yet such as the case of a common value to display.

Wednesday, December 5th, 2007

This post is based on this post, which is a great post in my opinion and since it already exists I didn’t see the need to rewrite the post so I suggest you go read it first.

The stuff that I am going to add are few observations I have and small implementation enhancement that I think helps the implementation to be even more intuitive.

First, a small overview.

Say you have a class User who has a name, country of residence and a birth date.

It makes sense that you have something like:

if (user.CountryOfResidence == Country.Chad ||
    user.CountryOfResidence == Country.Sudan)
{
    // Do something…
}

This code performs some special logic for a user that is coming from Africa and from a country that exists in our system. There is a good chance that code such as this condition is duplicated in a UI page and in a business logic service and maybe in some more places throughout the application. The problems with this are:

Unless the developer who wrote the code added documentation that states it checks that a user came from Africa, we can only guess what it means. It might just be a list of countries for all we know… You might say that it can be placed in a local private method like

if (IsUserFromAfrica(user))
{
    // Do something
}

so now it describes what it means but this still doesn’t solve the code duplication problem. What if now Angola is supported as an African country as well? You will still have to go and change all the occurrences of the condition whether it is inline or wrapped in a method.

By using the Specification Pattern the code will be transformed to this:

if (new UserFromAfricaSpecification().IsSatisfiedBy(user))
{
    // Do something…
}

Where UserFromAfricaSpecification is implemented like this:

public class UserFromAfricaSpecification :
    Specification<User>
{
    public override bool IsSatisfiedBy(User obj)
    {
        return obj.CountryOfResidence == Country.Chad ||
            obj.CountryOfResidence == Country.Sudan;
    }
}

The base class Specification can be found in the attached code.

By working with specifications like that, we get documented, reusable  and independently testable "libraries" of specifications.

Since conditions usually are business rules, which are always difficult to maintain and manage, the specification pattern comes very handy and this is the one thing I like the most about it.

As I wrote before, this post shows how the code is built. The code sample attached to my post is almost identical to the code there. The difference is mostly in one detail - specification composition can be performed using the & and | operators, and the ! operator is also available. This means that you can write a specification like this:

if ((new UserOlderThanSpecification(18) &
    (!new UserFromAfricaSpecification())).IsSatisfiedBy(user))
{
    // Do something…
}

Another use of the specification pattern is to define what we are looking for. The signature of the IsSatisfiedBy method matches the Predicate delegate signature and therefore can be used by the ForEach method of Array or List<> when looking for, say, a user who satisfies a certain condition:

List<User> africanUsers = allUsers.FindAll(
    new UserFromAfricaSpecification().IsSatisfiedBy);

where allUsers is of type List.

What I still don’t like about the current implementation is the fact the the new keyword is used to instantiate a specification instance. I have few ideas about that so expect a follow-up.

The example code for this post is here.

Jajah is the VoIP player that brought you web-activated telephony.