Code Smell: Primitive Obsession

We coders can't even keep track of a few primitives. Can we just accept that and adjust our style or do we want to continue obsessing over primitive obsession?

· 2 min read
Code Smell: Primitive Obsession

Technical Essays Referenced

UML example of taking what might be primitive types (Contact and SocialSecurity as string, in this case) and removing the primitive and substituting it with a user-defined type
public class Customer
{
    public string Name { get; private set; }
    public string Email { get; private set; }
 
    public Customer(string name, string email)
    {
        // Validate name
        if (string.IsNullOrWhiteSpace(name) || name.Length > 50)
            throw new ArgumentException("Name is invalid");
 
        // Validate e-mail
        if (string.IsNullOrWhiteSpace(email) || email.Length > 100)
            throw new ArgumentException("E-mail is invalid");
        if (!Regex.IsMatch(email, @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"))
            throw new ArgumentException("E-mail is invalid");
 
        Name = name;
        Email = email;
    }
 
    public void ChangeName(string name)
    {
        // Validate name
        if (string.IsNullOrWhiteSpace(name) || name.Length > 50)
            throw new ArgumentException("Name is invalid");
 
        Name = name;
    }
 
    public void ChangeEmail(string email)
    {
        // Validate e-mail
        if (string.IsNullOrWhiteSpace(email) || email.Length > 100)
            throw new ArgumentException("E-mail is invalid");
        if (!Regex.IsMatch(email, @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"))
            throw new ArgumentException("E-mail is invalid");
 
        Email = email;
    }
}
The author says that you can't keep using primitives! Your validation code will end up being duplicated and scattered all over the architecture! Well? Yes and no. It depends on what kind of architecture you're building. DRY can be a very bad thing in one scenario and absolutely necessary in another. Don't use a LOTR architecture strategy if you don't need to

(Also of note, from Lobsters reader @corbin, "How Futile are Mindless Assessments of Roundoff in Floating-Point Computation?")

A nice primitive obsession propaganda meme from the web

Related Articles

2021-10-22 Nerd Roundup
· 3 min read
2021-10-08 Nerd Roundup
· 6 min read
2021-10-01 Nerd Roundup
· 4 min read
2021-09-24 Nerd Roundup
· 3 min read
2021-09-17 Nerd Roundup
· 5 min read
2021-09-10 Nerd Roundup
· 3 min read