Protected attributes are great for encapsulating and controlling access to our properties. They might be warning us for another smell.
- Sub classification for code reuse purposes.
- Liskov substitution violation (SOLID principle).
- Possible subclass overrides.
- Favor composition
- Don’t subclassify attributes.
- Extract behavior to separate objects.
- Use traits (if available).
In languages supporting protected attributes we can avoid them by policy or have a warning of this smell.
Protected attributes are yet another tool we should use carefully. Every decision is a smell, and we should be very careful with attributes and inheritance.
Code Smell 11 — Subclassification for Code Reuse
Code reuse is good. But subclassing generates a static coupling.
Subclasses shouldn’t always share all characteristics of their parent class but will do so with inheritance. This can make a program’s design less flexible. It also introduces the possibility of calling methods on subclasses that don’t make sense or that cause errors because the methods don’t apply to the subclass.
This article is part of the CodeSmell Series.