tag:blogger.com,1999:blog-36345871.post2055882965573865070..comments2014-04-20T23:23:36.639-07:00Comments on Perl Alchemy - notes of a programmer: Dependency Injection or Removing Hardcoded Values?zbyhttp://www.blogger.com/profile/04636763782334128869noreply@blogger.comBlogger2125tag:blogger.com,1999:blog-36345871.post-84329934726030719462011-01-06T00:24:36.289-08:002011-01-06T00:24:36.289-08:00Yeah Moose takes over &#39;new&#39; and thus encou...Yeah Moose takes over &#39;new&#39; and thus encourages DI, but people do find workarounds by using some &#39;init&#39; or &#39;setup&#39; methods or using BUILDARGS or BUILD. This is material for another post.<br /><br />As to if DI follows from complete class encapsulation - that is entirely possible, but I think my approach is a bit more concrete and the explanation goes deeper.zbyhttp://www.blogger.com/profile/04636763782334128869noreply@blogger.comtag:blogger.com,1999:blog-36345871.post-51522829407395122062011-01-05T10:07:05.469-08:002011-01-05T10:07:05.469-08:00I believe you are overcomplicating things a little...I believe you are overcomplicating things a little bit. DI is the idea that your class encapsulation should be so complete and that your objects should really be blackboxes to the point where it doesn&#39;t really matter from where the constituent pieces come, but only that they behave/type as expected. When the OO paradigm is taken to the proper encapsulation level, DI is simply the natural conclusion reached. <br /><br />A code example illustrates this best:<br /><br /> package Foo;<br /> use Moose;<br /><br /> has logger =&gt; ( is =&gt; &#39;ro&#39;, isa =&gt;<br /> &#39;Logger&#39;, handles =&gt; [&#39;log&#39;], <br /> required =&gt; 1);<br /><br /> sub frobinate<br /> {<br /> shift-&gt;log(&#39;frobinate&#39;);<br /> }<br /><br />Foo doesn&#39;t care much about the logger, only that it is provided. It obviously depends on the logger being there when frobinate() is called, but it doesn&#39;t worry about constructing the logger. When you build your classes in such a fashion it becomes much easier to mock and test them. Your object graph becomes much cleaner.<br /><br />Instead of looking at it as refactoring or removing code, look at it as if the class is simply written as if some external resource will be provided and available for use. The complexity of your class will collapse. This also makes it easy to define the boundaries of responsibility between the pieces in your program.<br /><br />TL;DR<br />DI is the natural result when proper OO encapsulation occurs.NPEREZhttp://www.blogger.com/profile/07774396754686720265noreply@blogger.com