Over a million developers have joined DZone.

Communicating business rules with methods

· DevOps Zone

The DevOps Zone is brought to you in partnership with Sonatype Nexus. The Nexus Suite helps scale your DevOps delivery with continuous component intelligence integrated into development tools, including Eclipse, IntelliJ, Jenkins, Bamboo, SonarQube and more. Schedule a demo today

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.

The DevOps Zone is brought to you in partnership with Sonatype Nexus. Use the Nexus Suite to automate your software supply chain and ensure you're using the highest quality open source components at every step of the development lifecycle. Get Nexus today

Topics:

Published at DZone with permission of Jonas Gauffin, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}