Getting things is widespread and safe. But it is a very bad practice.
Problems
Naming
Information Hiding
Coupling
Encapsulation Violation
Mutability
Anemic Models
Solutions
Avoid Getters
Use domain names instead
Protect your implementation decisions.
Sample Code
Wrong
Right
Detection
Getters coincide in certain scenarios with a true responsibility. It will be reasonable for a window to return its color, and it may accidentally store it as color. So a color() method returning the attribute color might be a good solution.
getColor() breaks bijection since it is implementative and has no real counterpart on our mappers.
Most linters can warn us if they detect anemic models with getters and setters.
Tags
- Information Hiding
Conclusion
Getters and Setters are a poorly established practice. Instead of focusing on object behavior (essential), we are desperate to know object guts (accidental) and violate their implementation.
Relations
Code Smell 01 - Anemic Models
Maxi Contieri ・ Oct 20 '20
Code Smell 64 - Inappropriate Intimacy
Maxi Contieri ・ Mar 27 '21
More info
Credits
Photo by Vidar Nordli-Mathisen on Unsplash
The value of a prototype is in the education it gives you, not in the code itself.
Alan Cooper