Communicating business rules with methods

Do you use anemic models? i.e. having business classes like “User” without any methods but just properties instead? Do you want to do better but do not know how?

In OneTrueError we want to verify emails so that we can email notifications, password reset requests and invoices. As a small startup documentation is not something mandatory 🙂 Instead we try to write the code so that new team members can understand what we thought when we wrote the code.

We could for instance have set the email like this:

public class Account
{
    public Account(string userName)
    {
        if (userName == null) throw new ArgumentNullException("userName");
        UserName = userName;
    }

    public string UserName { get; private set; }
    public string Email { get; set; }
}

.. which would allow anyone to set the email to anything. But instead we have chosen the following solution:

public class Account
{
    public Account(string userName)
    {
        if (userName == null) throw new ArgumentNullException("userName");
        UserName = userName;
    }

    public string UserName { get; private set; }
    public string Email { get; private set; }

    public void SetVerifiedEmail(string email)
    {
        if (email == null) throw new ArgumentNullException("email");
        Email = email;
    }
}

Now, that doesn’t really protect us against anything (technically). But all developers that want to change the email address will be fully aware of that it must have been verified.

So methods is a really great way to explain business rules compared to properties. They also allow you to add sanity checks to catch errors earlier.