Sunday, January 12, 2014

Android Model-View-Presenter

There are a lot of conflicting recommendations around using the MVP pattern with Android activities. The two suggested approaches make different tradeoffs, and while one of the approaches looks good on the surface, it misses the point.

The first school of thought is that the view is the layout and the activity is the presenter. This approach is convenient because the view only needs to subclass a layout like RelativeLayout and the presenter already receives some of the interesting events such as onCreate, onResume, etc.

The second approach is cleaner from the presenter perspective. The goal of the MVP pattern is to separate the view logic from the view itself. Therefore, the presenter should be divorced from any kind of view specific hierarchy, such as extending Activity. This goal exists to make the presenter more testable, and it is worth the message forwarding from the activity (now the view) to the presenter.

It is fairly trivial to create a common AbstractPresenter and AbstractViewActivity that forward the most common events to the presenter: onCreate, onResume, onPause, onDestroy, onCreateOptionsMenu. Now it becomes much simpler to define the Presenter.View interface that extends your common view interface and provides the view specific methods such as setSelectedTab, enableMenuActions, or whatever interfaces you may need.

Also, by making the activity the view, the most trivial logic can be left in the view itself since only the most interesting logic needs to be tested in the presenter. For example, when handling a menu item action, a confirmation dialog may need to be shown. The real presenter logic takes place in the ok/positive button listener, and there is no need for the presenter to handle the logic of confirming the action with the user. It is actually the logic that taken when the ok button is selected that is the subject under test, so the ok button listener delegates this action to the presenter.onSomeInterestingAction.

No comments:

Post a Comment