Search code examples
javaandroiddependenciesmvp

Android MVP Dependency Rules


I've read and tested much about MVP patterns in Android, but I'm here to ask your opinion about what could be the best practice if I want to respect both the "Dependency Rule" and the MVP pattern.

How it is explained into many articles (see this link: http://fernandocejas.com/2014/09/03/architecting-android-the-clean-way/), our application must be divided into layers and only an outer layer can instantiate and use an inner layer. The inner layer receive all parameters (Variables, contexts, Views, etc.) and return response or use callbacks etc.

It is also a good practice to isolate the layers the more you can, through using interfaces and calling the interfaces instead of classes directly. (see the link: http://www.tinmegali.com/en/model-view-presenter-mvp-in-android-part-2/). In the link above the author specifies he doesn't use callback methods but interfaces to move from an inner layer to an outer layer (not respecting the dependency rule).

My questions about this are two:

1) is it better to use interface for both the calling class (outer layer refers to the interface of the class called) and the called class (inner layer refers to the interface of the class calling), or is it only necessary in one direction, for instance only outer class refers to interface of inner one?

2) because the external layer (the UI) creates all inner layers and through a simple screen rotation is destroyed and recreated, is it better (for the memory leak) to save the state (when it's needed), destroy inner classes and processes, and recreate them, or to istantiate in a static way (through Singleton or as instances of a class which extends Application class) all the classes which need to "survive" to rotation screen? Thanks to everyone!


Solution

  • I believe that MVP is somehow a Tuxedo development which means you have to separate everything and use interfaces for declaring different methods before implementing them. So my answer to your fist question is YES!

    Usually, in this type of situation, I think that I am the one who define layers and another junior developer is about to use the core which I have developed, so, it is better to limit his action and decrease his faults and error.

    About recreating, I would suggest using Dagger in proper way, which really stops you from recreating objects that have been generated before only because of a screen rotation! You can keep your lower layers declarations in memory and attach them to your new view after rotation.

    I would suggest to take a look at this sample repo which I have developed using MVP, Dagger, RxJava and Retrofit to get more familiar with best practices and new Android development methods:

    http://github.com/mmirhoseini/fyber_mobile_offers

    I hope it helps :)