Invisible objects have rules we need to enforce in a single point
TL;DR: Create Small objects and restrict your domain.
Problems
Bijection Fault
Repeated Code validation
Solutions
- 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
Software Engineering Great Quotes
Maxi Contieri ・ Dec 28 '20
This article is part of the CodeSmell Series.
Top comments (1)
Bug spotted: you're missing closing quotes in the last line of your "right" example.