DEV Community

loading...
Cover image for Code Smell 37 - Protected Attributes

Code Smell 37 - Protected Attributes

Maxi Contieri
Learn something new every day. - I am a senior software engineer working in industry, teaching and writing on software design, SOLID principles, DDD and TDD.
・1 min read

Protected attributes are great for encapsulating and controlling access to our properties. They might be warning us for another smell.

Problems

Solutions

  1. Favor composition
  2. Don't subclassify attributes.
  3. Extract behavior to separate objects.
  4. Use [traits](https://en.wikipedia.org/wiki/Trait_(computer_programming) (if available).

Wrong

Right

Detection

In languages supporting protected attributes we can avoid them by policy or have a warning of this smell.

Tags

  • Encapsulation

Conclusion

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.

Relations

More Info

Traits on Wikipedia

Credits

Photo by Jonathan Farber on Unsplash


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.

Steve Klabnik

Discussion (1)

Collapse
theminimalistdeveloper profile image
Rafael Dias Moreira

Loving the series!