Some objects are always together. Why don't we split them?
TL;DR: Make cohesive primitive objects travel together
-
Bad Cohesion
-
Duplicated Code
-
Validation Complexity
-
Readability
-
Maintainability
-
Extract Class
-
Find small objects
This smell is friends with primitive obsession.
If two or more primitive objects are glued together, with business logic repeated and rules between them, we need to find the existing concept on the bijection.
public class DinnerTable
{
public DinnerTable(Person guest, DateTime from, DateTime to)
{
Guest = guest;
From = from;
To = to;
}
private Person Guest;
private DateTime From;
private DateTime To;
}
public class TimeInterval
{
public TimeInterval(DateTime from, DateTime to)
{
if (from >= to)
{
throw new ArgumentException
("Invalid time interval:" +
" ’from’ must be earlier than ’to’.");
}
From = from;
To = to;
}
}
public DinnerTable(Person guest, DateTime from, DateTime to)
{
Guest = guest;
Interval = new TimeInterval(from, to);
}
// Even Better...
public DinnerTable(Person guest, Interval reservationTime)
{
Guest = guest;
Interval = reservationTime;
}
[X] Semi-Automatic
Detection based on cohesion patterns is available o a few linters.
- Cohesion
Group behavior in the right place and hide the primitive data.
Code Smell 122 - Primitive Obsession
Code Smell 27 - Associative Arrays
Photo by Dynamic Wang on Unsplash
The heart of the software is its ability to solve domain-related problems for its user. All other features, vital though they may be, support this basic purpose.
Eric Evans
Software Engineering Great Quotes
This article is part of the CodeSmell Series.