title: Mixing object construction with application logic
body: <p>I've started refactoring my code to make it testable. One area I've found a problem is where I've mixed object construction with application logic. If I have a constructor called <code>SomeClass</code> which performs application logic but also instantiates another class I run in to problems when I try to test:</p>
  
  <pre><code>function SomeClass() {
  
      //does lots of application type work
      //but then also instantiates a different object
      new AnotherClass();
  }
  </code></pre>
  
  <p>Testing becomes difficult because now I need to find a way to create <code>AnotherClass</code> in the test environment.</p>
  
  <p>I've dealt with this problem using dependency injection. So <code>SomeClass</code> takes an instance of <code>AnotherClass</code> as a parameter:</p>
  
  <pre><code>function SomeClass(anotherObj) {
  
  }
  </code></pre>
  
  <p>Problem with this is as far as I can see is all this does is defer the problem to somewhere else in my application. I still have to create the <code>anotherObj</code> from <code>AnotherClass</code> somewhere else in my code.</p>
  
  <p>This google testing article <a href="http://googletesting.blogspot.co.uk/2008/08/by-miko-hevery-so-you-decided-to.html" rel="nofollow">http://googletesting.blogspot.co.uk/2008/08/by-miko-hevery-so-you-decided-to.html</a> suggests:</p>
  
  <blockquote>
    <p>In order to have a testable code-base your application should have two
    kinds of classes. The factories, these are full of the "new" operators
    and are responsible for building the object graph of your application,
    but don't do anything.And the application logic classes which are devoid of the "new" operator and are responsible for doing work.</p>
  </blockquote>
  
  <p>This sounds exactly like my problem and the factory type pattern is what I need. So I tried something like:</p>
  
  <pre><code>function anotherClassFactory() {
      return new AnotherClass();
  }
  
  function SomeClass() {
      anotherClassFactory();
  }
  </code></pre>
  
  <p>But then <code>SomeClass</code> still has a dependency on the factory. How do I get around this correctly?</p>