Note that there are some explanatory texts on larger screens.

plurals
  1. POConstruction of a singleton class
    text
    copied!<p>An ethical question here. </p> <p>I'm planning on using several manager classes in my new project that will be performing various tasks across the whole project. These classes are singletons, but require construction based on parameters.</p> <p>As to when/where this construction has to happen, I have mixed feelings. I have these options so far:</p> <p><strong>Option A</strong></p> <p>It's easy to just pass these parameters to the <code>getInstance</code> method while having a default <code>null</code> value. On the very first call the parameters will be used, and any additional calls completely ignore them. </p> <p>While this works, doing so feels rather unlogical, for the following reasons:</p> <ul> <li><p><strong>It makes documentation unclear.</strong> <code>getInstance</code>' first parameter must be of type <code>Collection</code>, but can be <code>null</code>... what's going on here? You can argue that writing a line about this in the description will clear it up, but I'd prefer clarification to be unneccesary.</p></li> <li><p><strong>It feels faulty to pass <code>getInstance</code> any construction parameters.</strong> This is due to the fact that the method name does not explicity hint towards construction, making it unclear it will happen.</p></li> </ul> <p><strong>Option B</strong></p> <p>I'm thinking about a <code>setup</code> method. This method takes all parameters, calls the class constructor, and changes the internal class state to <code>initialized</code>. </p> <p>When calling the <code>getInstance</code> method prior to <code>setup</code>, it will throw a <code>NotInitializedException</code>. After setup has been called, any additional calls to <code>setup</code> will result in a <code>PreviouslyInitializedException</code>.</p> <p>After <code>setup</code> has been called, <code>getInstance</code> becomes available.</p> <p>Personally, this option appeals more to me. But it feels excessive.</p> <p>What option do you prefer? And why?</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