Classes are handy. We can call them and invoke them any time. Is this good?
TL;DR: Don't use your classes as a global point of access.
Problems
Coupling
Classes are global unless we use Namespaces.
Name polluting
Static Methods
Static Constants
Singletons
Solutions
Use namespaces, module qualifiers or similar
Avoid namespace polluting, keep the Global names as short as possible.
Class single Responsibility is to create instances.
Sample Code
Wrong
<?
final class StringUtilHelper {
static function reformatYYYYDDMMtoYYYYMMDD($date) {
}
}
class Singleton {
}
final class DatabaseAccessor extends Singleton {
}
Right
<?
namespace Date;
final class DateFormatter {
function reformatYYYYDDMMtoYYYYMMDD(Date $date) {
}
//function is not static since class single responsibility is to create instances and not be a library of utils
}
namespace OracleDatabase;
class DatabaseAccessor {
//Database is not a singleton and it is namespace scoped
}
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
Code Smell 18 — Static Functions
Maxi Contieri ・ Nov 6 '20
More info
Coupling: The one and only software design problem
Maxi Contieri ・ Feb 6 '21
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
Software Engineering Great Quotes
Maxi Contieri ・ Dec 28 '20
This article is part of the CodeSmell Series.
Top comments (3)
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.
There are a lot of languages supporting scoped Namespaces
Sadly, there's also many languages that Don't. Ruby comes to mind as an example.