Note that there are some explanatory texts on larger screens.

plurals
  1. POHow should I refactor my code to remove unnecessary singletons?
    primarykey
    data
    text
    <p>I was confused when I first started to see anti-singleton commentary. I have used the singleton pattern in some recent projects, and it was working out beautifully. So much so, in fact, that I have used it many, many times.</p> <p>Now, after running into some problems, reading <a href="https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons">this</a> SO question, and especially <a href="http://steve.yegge.googlepages.com/singleton-considered-stupid" rel="nofollow noreferrer">this</a> blog post, I understand the evil that I have brought into the world.</p> <p>So: How do I go about <i>removing</i> singletons from existing code?</p> <p>For example:<br> In a retail store management program, I used the MVC pattern. My Model objects describe the store, the user interface is the View, and I have a set of Controllers that act as liason between the two. Great. Except that I made the Store into a singleton (since the application only ever manages one store at a time), and I also made most of my Controller classes into singletons (one mainWindow, one menuBar, one productEditor...). Now, most of my Controller classes get access the other singletons like this:</p> <pre><code>Store managedStore = Store::getInstance(); managedStore.doSomething(); managedStore.doSomethingElse(); //etc. </code></pre> <p>Should I instead:</p> <ol> <li>Create one instance of each object and pass references to every object that needs access to them? <li>Use globals? <li>Something else? </ol> <p>Globals would still be bad, but at least they wouldn't be <a href="http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/" rel="nofollow noreferrer">pretending</a>.</p> <p>I see #1 quickly leading to horribly inflated constructor calls:</p> <pre><code>someVar = SomeControllerClass(managedStore, menuBar, editor, sasquatch, ...) </code></pre> <p>Has anyone else been through this yet? What is the OO way to give many individual classes acces to a common variable without it being a global or a singleton? </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

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