Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's not that the Singleton pattern is itself pure evil, but that is massively overused even in situations where it is inapproriate. Many developers think "Oh, I'll probably only ever need one of these so let's make it a singleton". In fact you should be thinking "I'll probably only ever need one of these, so let's construct one at the start of my program and pass references where it is needed."</p> <p>The first problem with singleton and testing is not so much because of the singleton but due to laziness. Because of the convenience of getting a singleton, the dependency on the singleton object is often embedded directly into the methods which makes it very difficult to change the singleton to another object with the same interface but with a different implementation (for example, a mock object).</p> <p>Instead of:</p> <pre><code>void foo() { Bar bar = Bar.getInstance(); // etc... } </code></pre> <p>prefer:</p> <pre><code>void foo(IBar bar) { // etc... } </code></pre> <p>Now you can test function <code>foo</code> with a mocked <code>bar</code> object which you can control. You've removed the dependency so that you can test <code>foo</code> without testing <code>bar</code>.</p> <p>The other problem with singletons and testing is when testing the singleton itself. A singleton is (by design) very difficult to reconstruct, so for example you can only test the singleton contructor once. It's also possible that the single instance of <code>Bar</code> retains state between tests, causing success or failure depending on the order that the tests are run.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload