title: Dependency injection and the observer pattern
body: <p>I find that fairly frequently in my code I do this (using Guice as my DI framework):</p>
  
  <pre><code>public class SomeObserver implements IObserver {
      @Inject
      SomeObserver(IObservable observable) {
          observable.subscribe(this);
      }
      // Snip
  }
  </code></pre>
  
  <p>It occurred to me recently that, when testing, I am now required to pass at least a mock into my program, which is not necessarily the worst thing, but it does depend on at least binding a dependency to that <code>IObservable</code> interface. Another option would be to, in production, do this:</p>
  
  <pre><code>public class SomeModule extends AbstractModule {
      // snip
  
      @Provides
      protected SomeObserver provideSomeObserver(IObservable observable) {
          SomeObserver newObject = new SomeObserver();
          newObject.subscribe(observable);
      }
  }
  </code></pre>
  
  <p>Then in testing, I don't have to even have a reference to the <code>Observable</code>. However, if I ever want to change the constructor, the module must change as well (which it doesn't in the first example).</p>
  
  <p>Which is better? Or is there an even better third option?</p>
  
  <hr>
  
  <p>Update: I want to talk about my use case a bit.</p>
  
  <p>Consider a data processing application, where a data source is the Observable. I don't want the data source to know about other parts of the system (<a href="https://en.wikipedia.org/wiki/Separation_of_concerns" rel="nofollow">Separation of Concerns</a>). The data is filtered into at least three different Observers, who work on independent tasks. I want to keep the data source swappable - for testing, separation of concerns, etc. reasons, so the data source just implements what I've defined to be a <code>Subscribable&lt;Observer&gt;</code> interface, and then you can just call <code>.subscribe(this)</code>.</p>
  
  <p>Then, I use dependency injection and modules to determine exactly how the wiring is going to be. This solution also allows me to <a href="https://en.wikipedia.org/wiki/Decorator_pattern" rel="nofollow">decorate</a> observables if I choose, using annotations to clarify the injections.</p>
  
  <p>So, essentially, I'm using Dependency Injection to manage the wiring, which is exactly what I originally thought it was for; creating, say, an <code>ObservationManager</code> seems like a lot of <a href="https://en.wikipedia.org/wiki/Boilerplate_code" rel="nofollow">boilerplate</a> for little gain. But again, I may be missing something.</p>