Note that there are some explanatory texts on larger screens.

plurals
  1. PODependency Injection and Runtime Object Creation
    text
    copied!<p>I've been trying to follow the principles of Dependency Injection, but <A HREF="http://misko.hevery.com/2008/10/21/dependency-injection-myth-reference-passing/" rel="nofollow noreferrer">after reading this article, I know I'm doing something wrong.</A></p> <p>Here's my situation: My application receives different types of physical mail. All the incoming mail passes through my <code>MailFunnel</code> object.</p> <p>While it's running, <code>MailFunnel</code> receives different types of messages from the outside: Box, Postcard and Magazine. </p> <p>Each mail type needs to be handled differently. For example, if a Box comes in, I may need to record the weight before delivering it. Consequently, I have <code>BoxHandler</code>, <code>PostcardHandler</code> and <code>MagazineHandler</code> objects.</p> <p>Each time a new message comes into my <code>MailFunnel</code>, I instantiate a <b>new</b> corresponding <code>MailHandler</code> object. </p> <p>For example:</p> <pre> class MailFunnel { void NewMailArrived( Mail mail ) { switch (mail.type) { case BOX: BoxHandler * bob = new BoxHandler(shreddingPolicy, maxWeightPolicy); bob->get_to_work(); break; case POSTCARD: PostcardHandler * frank = new PostcardHandler(coolPicturePolicy); frank->get_to_work(); break; case MAGAZINE: MagazineHandler * nancy = new MagazineHandler(censorPolicy); nancy->get_to_work(); break; } } private: MaxWeightPolcy & maxWeightPolicy; ShreddingPolicy & shreddingPolicy; CoolPicturePolicy & coolPicturePolicy; CensorPolicy & censorPolicy; } </pre> <p>On one hand, this is great because it means that if I get five different pieces of mail in, I immediately have five different <code>MailHandlers</code> working concurrently to take care of business. However, this also means that <a href="http://misko.hevery.com/2008/09/10/where-have-all-the-new-operators-gone/" rel="nofollow noreferrer">I'm mixing object creation with application logic</a> - a big no-no when it comes to Dependency Injection.</p> <p>Also, I have all these policy references hanging around in my <code>MailFunnel</code> object that <code>MailFunnel</code> really doesn't need. The only reason that <code>MailFunnel</code> has these objects is to pass them to the <code>MailHandler</code> constructors. Again, <A HREF="http://misko.hevery.com/2008/10/21/dependency-injection-myth-reference-passing/" rel="nofollow noreferrer">this is another thing I want to avoid</A>.</p> <p>All recommendations welcome. Thanks!</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