title: Constructor / Self-reference for instance variables
body: <p>How to best refactor a constructor in Java, which instantiates member/instance variables, which need a reference to the class which is going to be constructed/instantiated? I want to pass the dependency in the constructor as a parameter, to enable unit testing of methods which call methods on the instance variable.</p>
  
  <p>Basically it boils down to something like this:</p>
  
  <pre class="lang-java prettyprint-override"><code>final class Foo {
    private final Bar bar;
    ...
  
    Foo() {
      bar = new Bar(this);
  
      ...
    }
  }
  </code></pre>
  
  <p>However, all dependencies should be given by dependency injection / per parameter.</p>
  
  <p>Edit: My idea would be adding a factory as a parameter to the constructor and then call a method which passes this in a createInstance method in the methods, which use the instance variables:</p>
  
  <pre><code>final class Foo {
    private final BarFactory factory;
  
    Foo(BarFactory factory) {
      this.factory = Objects.nonNull(factory);
    }
  
    public void bla(String fooBar) { 
      final Bar bar = factory.create(this); 
      ...
    }
  }
  </code></pre>
  
  <p>So I can mock the factory.</p>