cover-img

Code Smell 28 - Setters

Avoid changing object state

22 November, 2022

4

4

0

The first exercise junior programmers do. IDEs, tutorial and senior developers keep teaching them this anti-pattern.

Problems

Mutability

Information Hiding

Anemic Models

Fail Fast

Integrity

Duplicated Code

Solutions

1.

Avoid Setters

2.

Set essential attributes on private initialization.

Examples

DTOs

Sample Code

Wrong

Mutation brings lots of problems
Information Hiding Violated

Right

Detection

First step will be to forbid public attributes (if language allows them).
Secondly, we will search for methods setXXXX(), analyzing method structure (should be an assignment to attribute xxxx).
We should not forbid methods setting accidental state since this is valid. They should not be named setters since they ask the object to change, but they don't set anything.

Exceptions

Setting attributes is safe for non-essential attributes.
But it has all drawbacks and considerations already mentioned.

Tags

Mutation

Information Hiding

Conclusion

Creating incomplete and anemic objects is a very bad practice violating mutability, fail fast principle and real world bijections.

Relations

More Info

Here is the full discussion on Setters

Credits

Object-oriented programming languages support encapsulation, thereby improving the ability of software to be reused, refined, tested, maintained, and extended. The full benefit of this support can only be realized if encapsulation is maximized during the design process.

Rebecca Wirfs-Brock
This article is part of the CodeSmell Series.

4

4

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.