Code Smell 18 — Static Functions

mcsee

Maxi Contieri

Posted on November 6, 2020

Code Smell 18 — Static Functions

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

Examples

  • Static class methods

  • Static attributes

Sample Code

Wrong

class DateStringHelper {
   static format(date) {
     return date.toString('yyyy-MM-dd'); ;    
  }
}


DateStringHelper.format(new Date());
Enter fullscreen mode Exit fullscreen mode

Right

class DateToStringFormatter {
   constructor(date){
      this.date = date;
   }

   englishFormat() {
     return this.date.toString('yyyy-MM-dd');    
  } 
}

new DateToStringFormatter(new Date()).englishFormat()


Enter fullscreen mode Exit fullscreen mode

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 too decouple.

Relations

More info

Credits

Photo by Alex Azabache on Unsplash


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.

Last update: 2021/06/28

💖 💪 🙅 🚩
mcsee
Maxi Contieri

Posted on November 6, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Code Smell 18 — Static Functions
codenewbie Code Smell 18 — Static Functions

November 6, 2020