Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are a couple of reasons why you should do this. Some good. Some bad. Lets start with a bad reason:</p> <ul> <li>Because everybody says so. Your coworker really should be able to explain why and you should ask him. Then judge his reasons.</li> </ul> <p>A Better reason: It really boils down to the single responsibility principle (the S of <a href="http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29" rel="nofollow">SOLID</a>)</p> <p>If you have a class A and that instantiates a class B and calls that instance it really is a strong hint that you have combined two responsibilities. (creating and calling or to phrase it differently: deciding who should do something and letting it do it). </p> <p>The remedy to this is to create the B instance outside of A and put it into A. Depending on the use case you have different options</p> <ul> <li><p>create a B outside of A and stuff it into A through the constructor. This is the correct way to go if A needs the B in multiple places and it needs exactly one.</p></li> <li><p>create a B outside of A and stuff it into A through some method call. This is the correct way if A needs the B(s) for a single interaction and needs/accept a different one on the next interaction.</p></li> <li><p>pass a factory into A which A can use to create Bs at will. This is appropriate when A needs multiple Bs.</p></li> </ul> <p>So this leaves the question: why is it so bad to use the constructor directly, instead of the factory, apart of violating some weired rule put up by a really smart person? If A creates Bs by calling the constructor for B it needs to know everything B needs for doing its work, which might be a lot of stuff and involve the necessety to create Cs, Ds and Es which themselves have dependencies which need to get created ... I think you see the point.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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