
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
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
This article is part of the CodeSmell Series.
About the author
I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.
Comments
Join the discussionInteresting article Maxi Contieri. If I get it right (see what I did there ) getters could be fine to be used if we assign a better name by removing the ¨get¨prefix and using a domain name instead. Another restriction is that we should use them only on safe operations, such as reading.
They become a problem when we expose the object internals to mutate its data from the outside, breaking encapsulation as consequence, is that right?
I think you would enjoy this blog post from 2018 about getters-setters as foundational to functional programming. I don't disagree with your point of view, but I think the title may be misleading.
Some interesting patterns such as the getter-getter and setter-setter can be used to achieve laziness in code. The article also shows how getters-setters are foundational for Promises, Observables, and AsyncIterables.
Code Smells
In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.





