mirror of
https://github.com/jupeter/clean-code-php.git
synced 2025-09-25 21:49:04 +02:00
Merge pull request #91 from peter-gribanov/singleton_desc
Expand description of Singleton
This commit is contained in:
@@ -672,7 +672,13 @@ And now you must use instance of `Configuration` in your application.
|
|||||||
|
|
||||||
### Don't use a Singleton pattern
|
### Don't use a Singleton pattern
|
||||||
|
|
||||||
Singleton is an [anti-pattern](https://en.wikipedia.org/wiki/Singleton_pattern).
|
Singleton is an [anti-pattern](https://en.wikipedia.org/wiki/Singleton_pattern). Paraphrased from Brian Button:
|
||||||
|
1. They are generally used as a **global instance**, why is that so bad? Because **you hide the dependencies** of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a [code smell](https://en.wikipedia.org/wiki/Code_smell).
|
||||||
|
2. They violate the [single responsibility principle](#single-responsibility-principle-srp): by virtue of the fact that **they control their own creation and lifecycle**.
|
||||||
|
3. They inherently cause code to be tightly [coupled](https://en.wikipedia.org/wiki/Coupling_%28computer_programming%29). This makes faking them out under **test rather difficult** in many cases.
|
||||||
|
4. They carry state around for the lifetime of the application. Another hit to testing since **you can end up with a situation where tests need to be ordered** which is a big no for unit tests. Why? Because each unit test should be independent from the other.
|
||||||
|
|
||||||
|
There is also very good thoughts by [Misko Hevery](http://misko.hevery.com/about/) about the [root of problem](http://misko.hevery.com/2008/08/25/root-cause-of-singletons/).
|
||||||
|
|
||||||
**Bad:**
|
**Bad:**
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user