سؤال

We're using the MVP pattern and GWT and I'm wondering how and when dependency injection should be used.

We have an App Controller, Presenters, Views and Model code. From reading the GIN tutorial at http://code.google.com/p/google-gin/wiki/GinTutorial#whb it would seem that you should use it at the highest level possible (so in the App Controller).

Should I use it to create my presenters, so I can do injector.getPresenter();

هل كانت مفيدة؟

المحلول

There is no required place in your app to use dependency injection. You could use it for one view or module, or use it everywhere. Either way, there's no reason not to make the injector available at the highest possible level (i.e., your App Controller).

As for when to use dependency injection, I'd say wherever you want to test a component of your system without having to load real heavy-weight dependencies.

Consider trying to test that this method returns 3:

public int returnsThree() {
  new WeatherChecker().checkTheWeather();
  return 3;
}

You wouldn't be able to without loading and running that big weather-checking dependency, meaning network access, timeout/failure handling, etc.

This is much better:

public int returnsThree(WeatherChecker dep) {
  dep.checkTheWeather();
  return 3;
}

That way, your test can just pass in a mock for this dependency, like:

public class MockWeatherChecker extends WeatherChecker {
  @Override
  public void checkTheWeather() {
    // do nothing
  }
}

If a component doesn't have any dependencies, which is unlikely, then you don't need to use dependency injection for it.

Presenters typically have a dependency on the view, which can easily be mocked out for faster tests (test using JUnit, not GWT tests). They may also depend on an EventBus, or something similar, which can easily be mocked out to focus on testing the presenter's logic.

Dependency injection is about facilitating testing as much as it is about separating responsibility.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top