cover-img

Code Smell 18 - Static Functions

Don't use static functions. They are global and utilities. Talk to objects instead.

23 October, 2022

3

3

0

Yet another global access coupled with laziness.

TL;DR: Don't use static functions. They are global and utilities. Talk to objects instead.

Problems

Coupling

Testability

Protocol Overloading

Cohesion

Solutions

Class Single Responsibility Principle is to create instance. Honor it.

Delegate method to instance.

Create stateless objects. Don't call them helpers.

Examples

Static class methods

Static attributes

Sample Code

Wrong

Right

Detection

We can enforce a policy to avoid static methods (all class methods but constructors).

Tags

Global

Libraries

Conclusion

Class are globals disguised. Polluting their protocol with "library methods" breaks cohesion and generates coupling. We should extract static with refactorings.
In most languages we cannot manipulate classes and use them polymorphically, so we can't mock them or plug them on tests.
Therefore, we have a global reference too difficult to decouple.

Relations

More info

Credits

There is no programming problem that can't be solved with one more level of indirection.

John McCarthy
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.