DEV Community

loading...
Cover image for Code Smell 60 - Global Classes

Code Smell 60 - Global Classes

mcsee profile image Maxi Contieri ・1 min read

Classes are handy. We can call them and invoke them any time. Is this good?

Problems

  • Coupling

  • Classes are global unless we use Namespaces.

  • Name polluting

  • Static Methods

  • Static Constants

  • Singletons

Solutions

  1. Use namespaces, module qualifiers or similar

  2. Avoid namespace polluting, keep the Global names as short as possible.

  3. Class single Responsibility is to create instances.

Sample Code

Wrong

Right

Detection

We can use almost any linter or create dependency rules searching for bad class references.

Tags

  • Globals

Conclusion

We should restrict our classes to small domains and expose just facades to the outside. This greatly reduces coupling.

Relations

More info

Credits

Photo by Alfons Morales on Unsplash


Write shy code — modules that don't reveal anything unnecessary to other modules and that don't rely on other modules' implementations.

Dave Thomas

Discussion (3)

pic
Editor guide
Collapse
darkwiiplayer profile image
DarkWiiPlayer

Namespaced values are just globals with a detour. If your Class is in a public namespace, it's a public class.

The only way to truly avoid these problems is a Lua-like system where there are no real globals and everything can be assigned to a name chosen by the user.

Collapse
mcsee profile image
Maxi Contieri Author

There are a lot of languages supporting scoped Namespaces

Collapse
darkwiiplayer profile image
DarkWiiPlayer

Sadly, there's also many languages that Don't. Ruby comes to mind as an example.