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.

  • Helton Moraes

    How about put the code in SetVerifiedEmail in the setter of Email property?

    • Marek

      Sounds good for single property-use-cases, but how to deal with it if such a method requires more parameters?

  • Helton Moraes

    (or to make “SetVerifiedEmail” private, and call it from Email setter…)

  • bblmr

    Like Helton Moraes, I’m wondering why not using the property setter.
    Is there something I miss or it’s just to use the auto properties and not have to declare a private member + the property (wich wouldn’t be a good reason…) ?

    • The purpose was to communicate business rules. Just having a public setter would require that those are communicated verbally or by comments. Using methods moves those rules into code.

  • Cristian

    DDD

    • DDD is so much more than just using methods. Using methods is just plain encapsulation, one of the core principles of object oriented programming.