# Code Smell 32 - Singletons

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

# Problems

- [Coupling](https://maximilianocontieri.com/coupling-the-one-and-only-software-design-problem)

- Testability.

- Accidental implementation problems.

- Multi threading issues.

- Static methods polluting.

- Object creation contract violation.

- [Bijection](https://mcsee.hashnode.dev/the-one-and-only-software-design-principle) mismatch.

- Memory issues.

- Premature Optimization.

%[https://mcsee.hashnode.dev/code-smell-20-premature-optimization]

# Solutions

1. Avoid it.

2. Use contextual unique objects.

3. Benchmark object creation.

# Examples

- Database Access

- Globals

- Loggers

- Helpers

%[https://maximilianocontieri.com/code-smell-22-helpers]

# Sample Code

## Wrong

%[https://gist.github.com/mcsee/5f0b4685e3af22e2a0a82f9f642c5c79]

God is the archetypical singleton example.

%[https://gist.github.com/mcsee/df78952fd4871362eaffcc6ce7ab6c94#file-christiangod-php]

%[https://gist.github.com/mcsee/e9a082aca6e2e7e4412d5da4290a5f0a#file-singletoncoupling-php]

## Right

%[https://gist.github.com/mcsee/48af2ebb8874c53f5aa5091c24c832e5]

# 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](https://en.wikipedia.org/wiki/Singleton_pattern).
 
# Tags

- Globals

# Conclusion

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

# Relations

%[https://maximilianocontieri.com/code-smell-06-too-clever-programmer]

%[https://maximilianocontieri.com/code-smell-25-pattern-abusers]

%[https://maximilianocontieri.com/code-smell-18-static-functions]

# More info

%[https://maximilianocontieri.com/singleton-the-root-of-all-evil]

%[https://97-things-every-x-should-know.gitbooks.io/97-things-every-programmer-should-know/content/en/thing_73/]

%[https://www.freecodecamp.org/news/singleton-design-pattern-pros-and-cons-e10f98e23d63/]

# Credits

Photo by <a href="https://unsplash.com/@miteneva">Maria Teneva</a> on <a href="https://unsplash.com/s/photos/rotten">Unsplash</a> 

* * *

> 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_

%[https://mcsee.hashnode.dev/software-engineering-great-quotes]

* * *

This article is part of the CodeSmell Series.

%[https://mcsee.hashnode.dev/how-to-find-the-stinky-parts-of-your-code]
