Code Smell 178 - Subsets Violation

Photo by Mona Eendra on Unsplash

Code Smell 178 - Subsets Violation

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

Maxi Contieri
·Nov 10, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Problems
  • Solutions
  • Context
  • Sample Code
  • Detection
  • Tags
  • Conclusion
  • Relations
  • More Info
  • Disclaimer
  • Credits

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

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");

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.

 
Share this