MVP architecture in Android development

MVP architecture in Android development

Recently, more and more people have started talking about architecture. So have my colleagues and engineers. Although I don't have a deep understanding of MVP and DDD, we decided to build our new project through MVP.

This article is a summary of my research and study of various articles and special discussions. It includes the following points:

  • Why are more and more people starting to pay attention to architecture?
  • First of all, what is MVP?
  • Which architecture is the best, MVC, MVVM or MVP?
  • Pros and Cons of MVP
  • Show me the code!!!

Unfortunately, this article will not cover:

  • Detailed and vivid code examples
  • How to write test code

***, I will tell you how to study these topics further.

By the way, I gave a talk about MVP architecture at a local seminar last week. This post is pretty much the same as the talk.

Introduction ~ Activity is the God class ~

First, let's think about why a clear software architecture is so urgent in Android development.

This paragraph is excerpted from "Code Complete Second Edition":

Avoid creating god classes. Avoid creating omniscient, omnipotent god classes. If a class needs to spend time retrieving data from other classes via Get() and Set() (that is, it needs to go deep into the business and tell them what to do), then these functions should be better organized in other classes rather than in the god class. (Riel 1996)

God classes are expensive to maintain, hard to understand what is going on, and difficult to test and extend, which is why it is a golden rule to avoid creating God classes.

However, in Android development, if you don't consider the architecture, the Activity class will tend to become larger and larger. This is because Android allows Views and other threads to coexist in the Activity. In fact, the biggest problem is that business logic and UI logic coexist in the Activity. This will increase the cost of testing and maintenance.

Activity is God

This is one of the reasons why a clear architecture is needed. Not only will it cause the Activity to become bloated, but it will also cause other problems, such as complicating the life cycle of Activity and Fragment, as well as data binding.

What is MVP?

MVP stands for Model, View and Presenter.

  • The View layer is responsible for handling user events and displaying the view part. In Android, it may be an Activity or Fragment class.
  • The Model layer is responsible for accessing data, which can be a remote Server API, a local database, or a SharedPreference.
  • The Presenter layer is the bridge connecting (or adapting) View and Model.

The following diagram is one of the patterns based on MVP architecture. View is the UI thread. Presenter is the adapter between View and Model. UseCase or Domain is in the Model layer and is responsible for getting or loading data from entities. The dependency rules are as follows:

The Dependency Injection

The key is that the high-level interface does not know the details of the low-level interface, or more accurately, the high-level interface cannot, should not, and must not know the details of the low-level interface, is (oriented towards) abstraction, and is detail-hiding.

The higher interfaces do not know about the details of the lower ones

Dependency rules?

Uncle Bob's "The Clean Architecture" describes what the rules for dependencies are.

Concentric circles divide the software into different areas. Generally, as the level goes deeper, the level of the software becomes higher. The outer circle is the implementation mechanism, and the inner circle is the core strategy.

Here is the summary of the above article:

Enitities:

  • Can be an object holding method functions
  • Can be a set of data structures or method functions
  • It is not important as long as it can be used by different applications in the project

Use Cases

  • Contains application-specific business rules
  • Carefully orchestrate the flow of data into or out of an Entity
  • Direct the Entity to directly use the business rules within the project scope to achieve the goal of the Use Case

Presenters Controllers

  • Convert the data in Use Case and Entity into the most convenient format
  • External systems, such as databases or web pages, can easily use this data
  • MVC architecture that fully includes the GUI

External Interfaces, UI, DB

  • All the details
  • Such as database details, web framework details, etc.

MVC, MVP or MVVM?

So which one is the best? Which one is better than the others? Can I choose just one?

The answer is, NO.

The motivation behind all these patterns is the same. That is how to avoid cluttered code, make it easy to perform unit testing, and create high-quality applications. That's it.

Of course, there are more than just these three architectural patterns. And none of them can be a silver bullet. They are just one of the architectural patterns, not the only way to solve the problem. These are just methods and means, not the purpose or goal.

Pros and Cons

OK, let's get back to the MVP architecture. We just learned what MVP is, discussed MVP and other popular architectures, and introduced the differences between MVC, MVP and MVVM. Here is a summary of the pros and cons of the MVP architecture:

**profit

  • Testable (TDD)
  • Maintainable (code reuse)
  • Easy Reviewe
  • Information hiding

**Cons

  • Redundant, especially for small app development
  • (Potentially) additional learning curve
  • It takes time before you start writing code (but I bet that designing the architecture is necessary for all project development)

show me the code!!!

This is just a small section of the MVP pattern. If you want to see more projects or live code examples, please refer to the "Links and Resources" at the end of the article. There are very rich and cleverly designed examples, most of which are hosted on Github so that you can clone, run on your device, and understand how it works.

First, define the interface for each View.

  1. /**
  2. * Interface classes for the Top   view  
  3. */
  4. public interface TopView {
  5.   
  6. /**
  7. * Initialize the view .
  8. *
  9. * eg the facade-pattern method for handling all Actionbar settings
  10. */
  11. void initViews();
  12.   
  13. /**
  14. * Open { <a href= "http://www.jobbole.com/members/57845349" > @link</a> DatePickerDialog}
  15. */
  16. void openDatePickerDialog();
  17.   
  18. /**
  19. * Start ListActivity
  20. */
  21. void startListActivity();
  22. }

Let's rewrite the TopView class. The key points are as follows:

  • TopActivity is only responsible for handling event monitoring or displaying each view component
  • All business logic must be delegated to the Presenter class
  • In MVP, View and Presenter are one-to-one (one-to-many in MVVM)
  1. public class TopActivity extends Activity implements TopView {
  2.   
  3. // here we use ButterKnife to inject views
  4. /**
  5. * Calendar Title
  6. */
  7. @Bind(R.id.calendar_title)
  8. TextView mCalendarTitle;
  9.   
  10. private TopPresenter mTopPresenter;
  11.   
  12. @Override
  13. protected void onCreate(Bundle savedInstanceState) {
  14. super.onCreate(savedInstanceState);
  15. setContentView(R.layout.activity_top);
  16. ButterKnife.bind(this);
  17.   
  18. // Save TopPresenter instance in a meber variable field
  19. mTopPresenter = new TopPresenter();
  20. mTopPresenter.onCreate(this);
  21. }
  22.   
  23. /*
  24. * Overrides method from the { <a href= "http://www.jobbole.com/members/57845349" > @link</a> TopView} interfaces
  25. */
  26.   
  27. @Override
  28. public void initViews() {
  29. // Actionbar settings
  30.   
  31. // set event listeners
  32. }
  33.   
  34. @Override
  35. public void openDatePickerDialog() {
  36. DatePickerFragment.newInstance().show(getSupportFragmentManager(),
  37. DatePickerFragment.TAG);
  38.   
  39. // do not write logic here... all logic must be passed to the Presenter
  40. mTopPresenter.updateCalendarDate();
  41. }
  42.   
  43. @Override
  44. public void startListActivity() {
  45. startActivity(new Intent(this, ListActivity.class));
  46. }
  47. }

This is the Presenter class. The most important thing is that Presenter is just an adapter bridge connecting View and Model. For example, TopUseCase#saveCalendarDate() hides the details of TopPresenter, and the same is true for TopView. You don't need to care about the data structure or how the business logic works. Therefore, you can perform unit testing on TopUseCase because the business logic is separated from the view layer.

  1. public class TopPresenter {
  2.   
  3. @Nullable
  4. private TopView mView;
  5.   
  6. private TopUseCase mUseCase;
  7.   
  8. public TopPresenter() {
  9. mUseCase = new TopUseCase();
  10. }
  11.   
  12. public void onCreate(@NonNull TopView topView) {
  13. mView = topView;
  14.   
  15. // here you call View 's implemented methods
  16. mView.initViews();
  17. }
  18.   
  19. public void updateCalendarDate() {
  20. // do not forget to   return if view instances are   null  
  21. if (mView == null ) {
  22. return ;
  23. }
  24.   
  25. // here logic comes
  26. String dateToDisplay = mUseCase.getDateToDisplay(mContext.getResources());
  27. mView.updateCalendarDate(dateToDisplay);
  28.   
  29. // here you save date , and this logic is hidden in UseCase class
  30. mUseCase.saveCalendarDate();
  31. }
  32. }

Of course, you can still perform unit testing even if the business logic is implemented in the Activity class, but it will be time-consuming and a bit complicated. It may take more time to run the App, instead, you should take advantage of the performance of the testing library, such as Robolectric.

Summarize

There is no silver bullet here, and MVP is just one of the solutions. It can be used in conjunction with other methods and can also be selectively used in different projects.

<<:  Mobile development fifth: 6 most popular positions for new programmers

>>:  Use Retrofit+RxJava+MVP to create a Material Design style APP

Recommend

10 Android Browsers to Improve Your Web Browsing Experience in 2018

【51CTO.com Quick Translation】An Internet browser ...

Best time to promote the most popular app categories in the App Store in 2015

A recent research report shows that weekends are ...

In-depth brand communication strategy—penetrate!

There are two things that left a deep impression ...

5 steps to teach you how to quickly get started with Weibo channel operations

As the gossip center of the entire Internet, Weib...

Hidden career crisis in the technological era

One day, our editorial group shared a news about ...

What is the best way to generate organic traffic on Tik Tok?

Nowadays, everyone on Douyin will try to get traf...