views:

237

answers:

3

We are developing an app using the MVP pattern, as described in this guide:

http://code.google.com/webtoolkit/articles/mvp-architecture.html

When creating the controller instance we do the following:

appController = new AppController(service, eventBus);
appController.go(RootPanel.get("SOME_SLOT"));

Now, when the controller creates a certain presenter, it does something like this:

sthPresenter = new SthPresenter(service, eventBus, new SthView());
sthPresenter.go();

The presenter than saves the eventBus and the service to a private field variable, and uses either as needed.

As the application grows, we have more and more presenters and views, so the question is can we use a different method of obtaining the service and the eventBus in the presenters, without passing a reference via the constructor of each presenter.

For example, creating a static field in the controller and just calling it with something like AppController.getService(). Maybe a singleton pattern.

Would a static field in the controller (or somewhere else) be a bad idea for this design. Keep in mind that the code is compiled to javascript, if that makes any difference.

A: 

Use a singleton and an Observer pattern. Make sure you only use high level events for your notifications, if not you will end up with a nightmare.

The code compiling to JavaScript is really transparent to you.

Romain Hippeau
A: 

I'd highly suggest dependency injection (DI). It allows you to avoid boilerplate code (singletons, etc.), global state and in general leads to a more testable code. Misko Hevery has some very interesting posts, including the very informative guide to writing testable code.

For DI in GWT you should use Gin - a wrapper around the popular Guice DI framework. I've been using it for a rather complex project and just using DI/Gin (and thinking how it should be applied most effectively) has definitely lead to a more "clean", testable code.

Igor Klimer
A: 

This is a situation very often encountered in GWT MVP applications. In my application, I use dependency injection (with GIN) to inject the event bus into presenters. Presenters themselves are singletons and can be eagerly instantiated if needed. Doing so, however, will greatly reduce the scalability of your application since a large app will require you to instantiate many presenters as soon as it starts up.

Correctly solving this problem yourself can be a bit involved. I suggest you take a look at the GWT-platform framework, which handles many of the more difficult problems associated with a GWT MVP app, including lazy instantiation of presenters and views, history management, efficient code splitting, etc.

Philippe Beaudoin