Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h2>I think that "Doing work in the constructor" is okay...</h2> <p>... as long as you don't violate <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" rel="noreferrer" title="Single Responsibility Principle &#40;SRP&#41;">Single Responsibility Principle (SRP)</a> and stick to using <a href="http://en.wikipedia.org/wiki/Dependency_injection" rel="noreferrer" title="Dependency Injection &#40;DI&#41;">Dependency Injection (DI)</a>. </p> <p>I have been asking myself this question too lately. And the motivation against doing work in the constructor that I have found are either:</p> <ul> <li>It makes it hard to test <ul> <li>All examples I have seen have been where <a href="http://en.wikipedia.org/wiki/Dependency_injection" rel="noreferrer" title="Dependency Injection &#40;DI&#41;">DI</a> wasn't used. It wasn't actually the fault of the constructor doing actual work.</li> </ul></li> <li>You might not need all the results that your constructor calculates, wasting processing time and it's hard to test in isolation. <ul> <li>This is basically a violation of <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" rel="noreferrer" title="Single Responsibility Principle &#40;SRP&#41;">SRP</a>, not a fault of the constructor doing work per say.</li> </ul></li> <li>Old compilers have/had trouble with exceptions thrown in constructors, hence you shouldn't do anything other than assign fields in constructors. <ul> <li>I don't think it's a good idea to write new code taking historical compiler deficiencies into account. We might as well do away with C++11 and all that is good all together if we do.</li> </ul></li> </ul> <h2>My opinion is that...</h2> <p>... if your constructor needs to do work for it to adhere to <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="noreferrer" title="Resource Aquisition Is Initialization &#40;RAII&#41;">Resource Acquisition Is Initialization (RAII)</a> and the class does not violate <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" rel="noreferrer" title="Single Responsibility Principle &#40;SRP&#41;">SRP</a> and <a href="http://en.wikipedia.org/wiki/Dependency_injection" rel="noreferrer" title="Dependency Injection &#40;DI&#41;">DI</a> is properly used; Then doing work in the constructor is A-Okay! You can even throw an exception if you'd like to prevent usage of a class object whose initialization failed completely instead of relying on the user to check some return value.</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