Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Communicating business rules with methods

DZone's Guide to

Communicating business rules with methods

· DevOps Zone ·
Free Resource

Learn more about how CareerBuilder was able to resolve customer issues 5x faster by using Scalyr, the fastest log management tool on the market. 

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.

Find out more about how Scalyr built a proprietary database that does not use text indexing for their log management tool.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}