DEV Community

Cover image for Code Smell 178 - Subsets Violation
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

Code Smell 178 - Subsets Violation

Invisible objects have rules we need to enforce in a single point

TL;DR: Create Small objects and restrict your domain.

Problems

Solutions

  1. Create small objects and validate the domain.

Context

This is a primitive obsession smell.

EmailAddresses are a subset of string.

Valid Ages are a subset of Real.

Ports are a subset of Integers.

A wordle word is a subset of String.

Sample Code

Wrong

destination = "destination@example.com"

destination = "destination.example.com"
// No error thrown
Enter fullscreen mode Exit fullscreen mode

Right

public class EmailAddress {
    public String emailAddress;

    public EmailAddress(String address) {
        string expressions = @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$";
        if (!Regex.IsMatch(email, expressions) {
          throw new Exception('Invalid address');
        }
        this.emailAddress = address;
    }
}

destination = new EmailAddress("destination@example.com");
Enter fullscreen mode Exit fullscreen mode

Not to be confused with the anemic Java version

Detection

[X] Manual

This is a semantic smell.

Tags

  • Primitive Obsession

Conclusion

We need to be loyal to the bijection of the real world.

Subsets are very important for early validations and fail fast principle.

Relations

More Info

Disclaimer

Code Smells are just my opinion.

Credits

Photo by Mona Eendra on Unsplash


Every craftsman starts his or her journey with a basic set of good-quality tools.

Andrew Hunt


This article is part of the CodeSmell Series.

Latest comments (1)

Collapse
 
moopet profile image
Ben Sinclair

Bug spotted: you're missing closing quotes in the last line of your "right" example.