Code Smell 32 - Singletons

Maxi Contieri - Nov 23 '20 - - Dev Community

The most used and (in)famous design pattern in the world is causing us great harm.

Problems

  • Coupling

  • Testability

  • Accidental implementation problems.

  • Multi threading issues.

  • Static methods polluting.

  • Object creation contract violation.

  • Bijection mismatch.

  • Memory issues.

  • Premature Optimization.

Solutions

  1. Avoid it.

  2. Use contextual unique objects.

  3. Benchmark object creation.

Examples

  • Database Access

  • Globals

  • Loggers

  • Helpers

Sample Code

Wrong

God is the archetypical singleton example.

Right

Detection

This is a design pattern. We should avoid it by policy.

We can add linter rules for patterns like 'getInstance()' so new developers cannot infect code with this anti-pattern.

Tags

  • Globals

Conclusion

This is an historical mistake already acknowledged by the community. Nevertheless, lazy developers bring it again and again. We need to reach a consensus on its drawbacks.

Relations

More info

Credits

Photo by Maria Teneva on Unsplash


The Diagram is Not the Model. The model is not the diagram. It is an abstraction, a set of concepts and relationships between them.

Eric Evans

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .