cover-img

Code Smell 37 - Protected Attributes

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

22 December, 2022

9

9

0

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

Problems

Sub classification for code reuse purposes.

Liskov substitution violation (SOLID principle).

Possible subclass overrides.

Solutions

1.

Favor composition

2.

Don't subclassify attributes.

3.

Extract behavior to separate objects.

4.

Use traits (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

Credits

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
This article is part of the CodeSmell Series.

9

9

0

Maxi Contieri

Buenos Aires, Argentina

🎓Learn something new every day.📆 💻CS software engineer 👷coding👨🏽‍🏫teaching ✍🏾writing 🎨Software Design 🏢SOLID 🌉TDD 👴Legacy 💩Code Smells

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.