Monday, September 20, 2010

Generic MVP with Properties and binding

A few months ago at Oxen we started an Android project. It was our first Android project (which made us very happy since we're working for iPhone until that moment :P - goodbye Objective C, at least for a while).

The application required a lot of forms (login, signup, etc.) and we built an ad-hoc FormBuilder class that dynamically binded UI fields to model beans. But this was an application-specific solution. We realized that Android didn't provided a form-to-bean binding facility.

For future projects, we stared a proof-of-concept: to build a generic binder for Android. After reading some sites explaining the Model View Presenter pattern, we thought that it would be possible to create a generic MVP implementation, not just for android, but in a technology-agnostic way.

Our first try was to abstract property and event acces. We built two interfaces:

public interface ActionAccessor {
   Observable getActionNotifier();


public interface PropertyAccessor extends ActionAccessor {
    Object getValue();
    void setValue(Object newValue);

Plus, we created a Binder class that connects properties, propagating changes from one to another. This allowed us to build a generic view presenter, with a generic presentation model, binded to both, UI components and to a bean model. We tested it creating both, Vaadin and Swing PropertyAccessors.

This model could be used to implement validations and data conversion.

The problem was that using such accessors was very verbose. We solved it by creating a name-convention-bean-like dynamic proxy. All this seemed to fit well.

When we where about to upload this proof-of-concept to Oxen Java Commons, I read the following links (from a post on The Server Side):

The idea of using a class for accessing properties instead of using name convention based beans seemed to fit very well. With that, the proxy will not be necessary. In fact, the author was promoting exactly the oposite idea: deprecating beans!!!

So, we made a refactor of the code to follow this approach. We used an interface instead of a Property class and added an Observable interface in order to handle events. The results are explained here:

We put a simple example where the same presenter is binded to Vaadin and Swing. Also, we created an Android implementation:

which was the first motivation for all of this.

This is just a proof-of-concept. Maybe it makes no sense to create too much verbose code just to make a presenter independent. Or maybe yes (we'll know after implementing this in a project).

The main doubt is if this model can be applied more generically, not just for simple forms (for example, for UIs with data lists).

No comments:

Post a Comment