Stop thinking of data as attributes. They are only needed to back your behavior
TL;DR: Don't focus on accidental properties. You won't need many of them.
Problems
Anemic Models
Properties bloating
YAGNI violation
Solutions
- Create attributes only to support your methods (behavior).
Context
Whenever they want to model a person or an employee, junior programmers or students add an attribute 'id' or 'name' without thinking if they are really going to need them.
We need to add attributes 'on-demand' when there's enough evidence. Objects are not 'data holders'.
Sample Code
Wrong
class PersonInQueue
attr_accessor :name, :job
def initialize(name, job)
@name = name
@job = job
end
end
Right
class PersonInQueue
def moveForwardOnePosition
# implement protocol
end
end
Detection
[X] Semi-Automatic
We can detect unused attributes.
But in many cases, we need an excellent designer to validate the actual need.
Tags
- Anemic
Conclusion
Start designing your objects from the protocol.
Add attributes only when needed.
Relations
Code Smell 144 - Fungible Objects
Maxi Contieri ・ Jun 25 '22
Code Smell 01 - Anemic Models
Maxi Contieri ・ Oct 20 '20
Credits
Photo by Melanie Pongratz on Unsplash
Object thinking focuses our attention on the problem space rather than the solution space.
David West
Software Engineering Great Quotes
Maxi Contieri ・ Dec 28 '20
This article is part of the CodeSmell Series.