cover-img

Code Smell 35 - State as Properties

When an object changes its state the best solution is to change the attribute, isn't it?

9 December, 2022

3

3

0

When an object changes its state the best solution is to change the attribute, isn't it?

Problems

Mutability

Attributes polluting

Setters

Solutions

1 - Model states as mathematical set inclusion.
2 - State is accidental, take it away from the object.

Examples

State diagrams

Sample Code

Wrong

Right

Detection

If we want to be extreme, we should consider every setter to be a potential state change. Linters can warn us. But we might end up getting too many false positives.

Exceptions

Over Design

Performance issues (if a serious benchmark supports it).

Tags

Mutation

Conclusion

This technique is very elegant but can lead to over design. For example changing a visual component its color should be a counterexample to this smell.
We should be aware and very caution like with any other smell.
They are hints and not rigid rules.

Relations

More Info

Credits

Photo by Tom Crew on Unsplash

First make the change easy (warning: this might be hard), then make the easy change.

Kent Beck
This article is part of the CodeSmell Series.

3

3

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.