Android & MVC Pattern

MVC (Model-View-Controller) is a design pattern that separates the user interface (View) and the business rules and data (Model) using a mediator (Controller) to connect the model to the view. All objects in the application must be Model object, View object or Controller object.

Model Object
Model objects model the things the application is concerned with. This is the data layer, responsible for managing the business logic and handling network or database API. For example, user, product, photo on a server, a television show. These objects have no knowledge of the UI and are just concerned with holding and managing data. Model classes are the custom classes the developer creates.

View Object
If you see it on screen, it is a view. View objects know how to draw themselves on the screen and respond to user touches. All the view objects in the application compose the view layer.

Controller Object
These objects tie the view and model objects. They contain the application logic. Controllers are designed to respond to various events triggered by view objects and to manage the flow of data to and from model objects and the view. In Android, controllers are usually subclasses of Activity, Fragment or Service.

Communication in this architectural pattern

Model and View objects do not talk to each other directly. The controller sits in the middle of everything, receiving messages from some objects and sending out instructions to other objects.

[1] Credits: Android Programming: The Big Nerd Ranch Guide

Advantages

MVC makes classes easier to reuse. A class with restricted responsibilities is easier to reuse than the class with fingers in every pie. Views can be updated without any concern about what changes to make in model classes. The model can be separated and dealt with independently without having to do anything with UI components in the application. Even the application template can be exported as a library so that another developer can use it in their application or so that you can use it in your next app.

Conclusion

Since the user interface changes a lot compared to the business logic of the application, it is better to separate the user interface functionality from the data logic. Both View and Controller depend on the Model for getting the data and updating the data respectively. Model can be tested independently which makes it easier to maintain the application in the long run.

Next time when you create a file, always ask yourself: What component of the MVC pattern does it represent? If you can’t decide, you may need to refactor the code.

Leave a Reply