Yet another global access coupled with laziness.
TL;DR: Don't use static functions. They are global and utilities. Talk to objects instead.
-
Coupling
-
Testability
-
Protocol Overloading
-
Cohesion
-
Class Single Responsibility Principle is to create instance. Honor it.
-
Delegate method to instance.
-
Create stateless objects. Don't call them helpers.
-
Static class methods
-
Static attributes
class DateStringHelper {
static format(date) {
return date.toString('yyyy-MM-dd');
}
}
DateStringHelper.format(new Date());
class DateToStringFormatter {
constructor(date) {
this.date = date;
}
englishFormat() {
return this.date.toString('yyyy-MM-dd');
}
}
new DateToStringFormatter(new Date()).englishFormat()
We can enforce a policy to avoid static methods (all class methods but constructors).
-
Global
-
Libraries
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.
Singleton - The root of all evil
Code Smell 112 - Testing Private Methods
How to Decouple a Legacy System
Photo by Alex Azabache on Unsplash
There is no programming problem that can't be solved with one more level of indirection.
John McCarthy
Software Engineering Great Quotes
This article is part of the CodeSmell Series.