MVC Architectural Pattern in Android – Part 1

Model View Controller (MVC) is one of the most common architectural patterns in software. It’s used to build maintainable GUI systems and its implementations exist in pretty much all languages and GUI frameworks. In this series of posts, I’ll describe the best implementation of MVC for Android applications.

All concepts will be demonstrated using open-source tutorial Android application.

Before we jump into the depths of Android architecture, however, allow me to address one common concern. It’s 2020 now, so you might wonder whether an article written back in 2015 is still relevant. After all, since I wrote this post, Android ecosystem changed quite a bit. In addition, Google introduced so-called “architecture components” and they recommend using MVVM architectural pattern today.

My answer to the above concerns is simple: I still use MVC in 2020 and I believe that it’s the best way to develop Android applications. In addition, my clients routinely choose MVC over MVVM after I show them the trade-offs, my students choose MVC after taking my courses and many readers of this blog adopted MVC over the years with great success. So, yeah, MVC is at least as relevant in 2020 as it was in 2015.

The Importance of MVC

Consider this statement by Robert “Uncle Bob” Martin:

The only way to make the deadline—the only way to go fast—is to keep the code as clean as possible at all times.

Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship

Proper MVC implementation has the following characteristics:

  • Readable and maintainable code
  • Decoupled responsibilities
  • Modular design
  • Testable code
  • Code which is fun to work with

All the above characteristics are generally associated with “clean code”. Therefore, following Uncle Bob’s reasoning, adoption of MVC allows you to “go faster” with your Android applications.

Historical Context

Historically, Android was poorly designed and there had been absolutely no architectural guidelines. Official tutorials demonstrated how to put all applications’ logic inside Activities and Fragments, and developers did exactly that for many years (and, in some cases, still do).

Sure enough, this approach led to ever-growing classes that had thousands upon thousands of lines of code inside them. The pain was real and many seasoned Android developers have horror stories about maintaining these apps.

Slowly, as community members got hands on experience with the platform, better ways to write applications emerged. The idea of separating UI logic from the rest of the application long predates Android, but it took some time until it penetrated into Android world and became widespread.

The earliest article which discussed presentation layer architectures in Android dates back to November 2010. It is titled Android Architecture: Message-based MVC and had been published by Ivan Memruk on his blog Mind The Robot. Although the article is very old and some techniques shown there are no longer used, the fundamental pattern that Ivan showed is exactly what we call MVP today. It’s not a typo: the same pattern that Ivan described as MVC became MVP over the years. We’ll get back to this point later in this article.

Then, in November 2011, Josh Musselwhite started a series of 9(!) posts about Android Architecture. In this series Josh expanded upon Ivan’s ideas and polished some implementation details. Then. in July 2012, Josh writes 10th post in the series titled The Activity Revisited. In this post Josh revolutionized Android development by expressing the idea that Activity is not a view in MVC, but a controller.

I read Ivan’s and Josh’s articles in 2014, as part of my own quest after best practices for Android development, and was immediately sold on their ideas. In the article titled Activities in Android are not UI Elements I explain why Activities should not contain UI logic and naturally fit into controllers role. The series of posts that you’re reading now expands on that theoretical aspect and demonstrates how to actually implement a solid MVC architectural pattern in real Android application.

Model? View? Controller? Presenter?

Now let’s discuss the similarities between MVC and MVP, both of which are architectural patterns. The idea behind them is that many software systems that have user interfaces can be roughly divided into three components:

  • The component that encapsulates domain logic and stores system’s domain state (whether persistent or not). That’s a Model.
  • The component that handles input-output from/to the user. That’s a View.
  • The component that controls user’s navigation within the app, processes user input and acts upon changes in domain state. That’s Controller/Presenter.

Components of a good MVC/MVP implementation should be decoupled as much as possible. For example, it should be possible to switch from one input/output entity (View) to another, or to change the location or the type of persistent storage mechanism (Model) without affecting other components.

Difference Between MVC and MVP

Unfortunately, there is no universally agreed definition for either MVC or MVP. You can find many descriptions on the web, some of which differ substantially. [If you are curious to see how different people interpret these patterns, read this thread on StackOverflow.]

Therefore, before we begin our discussion, we shall omit any ambiguity by providing a concrete definition for each pattern.

So, let’s put “popular” MVC and MVP interpretations side by side and compare them:

MVC_MVP

As you can see, these architectural patterns are very similar. The key differences are:

  1. In MVC, the view gets notified of any change in model’s state by the model itself. In MVP, the view knows nothing about the model, and it becomes presenter’s job to fetch the up to date data from the model, understand whether the view should be updated and bind a new data to the view.
  2. Views in MVC tend to have more logic in them because they are responsible for handling notifications from the model. In MVP, the same logic is located in the presenter, which makes the views very “dumb” – their sole purpose becomes rendering of the data that was bound to them by the presenter and capturing user input.

The bottom line is that in MVC the view is aware of model’s existence, whereas in MVP both the view and the model know nothing about each other.

Activity is not View

Given that “classical” Activity with thousands of lines of code in it would behave as both the view and the controller/presenter, in order to implement MVC or MVP we need to decide which of these responsibilities should be extracted from it. This question is not trivial, and there is no consensus in Android community as to which approach is better.

Many other implementations of MVx designate Activity as view and attempt to extract the controller functionality (sometimes they call that controller “ViewModel”, but it doesn’t change its purpose). I don’t think that this is the optimal approach and prefer to see Activity as contoller and extract view functionality. In my other article titled Activities in Android are not UI elements I explained why that’s the case.

MVC For The Win

We’ve already seen that MVP and MVC architectural patterns (as defined above) are very similar. Still, we need to choose just one of them.

My personal opinion is that the interaction mode described as MVP is better suited for Android because it’s cleaner to have independent view and model components. If we allow the view and the model to communicate directly, we might end up in a situation when the view needs to become aware of lifecycle events. Since these events are not directly related to UI management, making the view aware of them breaks the abstraction of application’s UI.

Since complete UI abstraction is very important for achieving “clean code”, I prefer MVP “mode” over MVC “mode” for Android development.

However, for historical reasons described above, I called this architectural pattern MVC. And let’s be honest: since MVC and MVP are very similar and developers don’t agree on these definitions anyway, the distinction isn’t really important. In addition, since the “standard” MVP in Android designates Activity as a view, it makes sense to use another name for a pattern that is so much better than that. Therefore, even though the architectural pattern you’ll learn here corresponds to MVP diagram above, I’ll call it MVC.

Luckily for us, this name is widely recognized and relatively vacant in Android ecosystem.

Native Support for MVC in Android

One very interesting question in this context is whether Android supports MVC “natively”. Just to be clear: the question is not whether Google recommends MVC (currently, they’re not as of 2016, some other variants of MVx patterns became officially promoted by Google), but whether Android makes it simple to adopt this architectural pattern.

The problem arises if you try to separate view and controller functionality. For example, the following code snippet was copied from Android Developers website:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Set the user interface layout for this Activity
    // The layout file is defined in the project res/layout/main_activity.xml file
    setContentView(R.layout.main_activity);

    // Initialize member TextView so we can manipulate it later
    mTextView = (TextView) findViewById(R.id.text_message);

    // Make sure we're running on Honeycomb or higher to use ActionBar APIs
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // For the main activity, make sure the app icon in the action bar
        // does not behave as a button
        ActionBar actionBar = getActionBar();
        actionBar.setHomeButtonEnabled(false);
    }
}

Let’s forget for a moment that this code snippet is trivial and analyze it in terms of view and controller responsibilities:

  • onCreate() is a “lifecycle” method which is called by Android framework in response to framework’s internal state transitions. These transitions might or might not be related to user’s actions in the application, but the application never calls onCreate() directly.
    You might get an impression that this method belongs to the “view” part of MVC because setContentView() is called along the way, but, in fact, setContentView() is a standard binding of a view performed by the controller.
    In addition, onCreate() (and other “lifecycle” methods) takes care of models initialization and binding, resources allocation and app’s state management. All these are controller responsibilities.
  • Activity also manages the UI of the application. In the above code snippet there are just two references to UI elements (R.layout.main_activity and R.id.text_message), but it is a widespread practice to place all UI code in Activity.

The unfortunate conclusion is that in Android, by default, Activities take on both view and controller responsibilities. Thererfore, if we want to implement MVC architectural pattern, it is up to us to enforce separation of concerns manually.

Conclusion

In this post we reviewed MVC and MVP architectural patterns in general, and also discussed their history and applicability in context of Android development.

The next post (part 2) shows how to abstract UI logic into “view” component.

Thanks for reading. You can leave your comments and questions below, and consider subscribing to our newsletter if you liked this post.

25 thoughts on “MVC Architectural Pattern in Android – Part 1”

  1. how about MVVM on Android? could you write useful post about it? which is better and we can simply manage Activity lifeCycle?

    Reply
    • As I said in the post, there is no universally agreed definition for any MVx pattern, therefore I can’t really know what you mean by MVVM. Some people even call the same pattern I propose here MVVM, and I don’t argue with them 🙂

      Reply
      • Hi, Vasiliy. I just read your message from stackoverflow.com. Actually I had to post that question about MVC and MVP after reading your posts here because I don’t get it clearly from here. Also, I don’t have any practical experience in development of Android. All I have is the conceptual idea of MVC(putting all things together) from my tutor. Even my tutor couldn’t well explain the differences between design patterns and said in China there’re many posts up there in the Internet regarding these patterns but variants of those abound as well. People hold their concepts of design patterns based on their own understandings of them, hence no unity. Sometimes I read an article from an accredited Android master on MVP, all in explicitly details, just when I thought I finally had a basic understanding of what’s going on with this pattern, I read the comments below, there’re voices that disagree. I am struggling to find an example from an authoritative source to learn but failed to find one, even googlesamples from github, too complex….and also I get confused with business logic, how to define business logic? Say a login interface(UI), does input username or password count as business logic? Does click the login button count as business logic? What can be included as business logic? Is there a rule of thumb? Thank you!

        Reply
        • Hello Alex,
          Thank you for your questions.
          I tend to agree with your tutor about MVx family of patterns (MVx = MVC or MVP or MVVM or etc.) – there is no universally agreed definition for them. I myself was thinking a lot about what is the main characteristic of MVx patterns. What I concluded is that if application’s UI logic is being encapsulated into independent components that can be easily replaced with alternative implementations, then this application can probably be seen as MVx.
          But even if we adopt the above heuristic for the definition of MVx family of patterns, we would still need to define “UI logic” (or its complement – “business logic”). This is a non-trivial task by itself.
          The heuristic that I use for UI logic is the following: if I change input method from GUI to command line, which parts of my application become obsolete? The parts that are not used anymore (because the user’s input obtained via command line) constitute the “UI logic”.
          Applying this heuristic to your examples show the following 1) UI elements that allow the user to input username/password belong to “UI logic” 2) Login button and the associated click event belongs to “UI logic”.
          And one last piece of advice: it will be better for you to get practical experience in Android development (e.g. constructing simple, but complete application) before you deep dive into advanced stuff. Since Android does not have a pre-defined “template” for any of MVx patterns, discussions about them immediately falls into “advanced” category.

          Reply
          • I see, thank you for your patience in answering my question. Your advice of defining logic coupled with how you think along the way does help me in codes reading and writing. I will practice that. Apologize that I may have misled you by saying practical experience, by that, I meant practical working experience. I came out of a short-term training school with hands-on experience in Android development only. And I got canned recently shortly after I put my finger on that project. Guessed I didn’t make them happy because of either low efficiency or incompetence. What I have learned from the training school is far different from the development of projects in real world. In school, the teachers use MVC only and do not emphasize much on distinguish what’s business logic and what’s model or things like that. On an unrelated note, is there a chance that you would begin to recommend books on Android once a while? I know you’re busy with your new project IDoCare. Please do not reply “Google does.”, XD! Thank you!

          • Alex,
            I was sad to hear about your first professional experience as Android Developer. However, in my opinion, the mere fact that you seek for information and ask for books advice is a strong indication that you’ll end up being an excellent developer. I’m not trying to be polite here – most Android developers that I met hadn’t ever read a book on software development. Those who had clearly stand out.
            As for books – this is a great idea. I’ll write a post on the topic. However, I’m not aware of many books about Android development and personally read just two. Unfortunately, I can’t recommend either of them. But if you’re serious about software development, then get a copy of Steve McConnell’s Code Complete 2. It is long (800+ pages), but its content is pure gold. At the end of a day, Android development is software development at its core.

  2. Hi Vasiliy. Thanks for these great posts. I don’t understand the following content well.
    “If we allow the view and the model to communicate directly, we might end up in a situation when the view needs to become aware of Activity or Fragment life-cycle events.”

    Could you give an example of this?

    As I understood, when View and Model communicate directly, they are changed based on user interactions such as entering some search keyword, performing a query and/or showing query results from the network. It seems not related to life-cycle callbacks (onCreate( ) etc.).

    I have very limited experience in Android. Forgive me if it sound naive.

    Reply
    • Hello Jack. You’re right – this statement requires justification.
      Except for querying the model, we will usually also want to register observers that will be notified when the model is changed in some way. These observers must be unregistered from the model when view/controller pair is no longer needed (e.g. user navigated to different screen). Forgetting unregistering the observer might cause memory leaks in some cases. Register and unregister actions are usually done in controller’s onStart() and onStop() methods respectively. If you delegate this functionality to MVC view, then we can register observers in constructor, but there is no corresponding “destructor”.
      In order to prevent memory leaks, we’ll need to introduce some sort of life-cycle into MVC views. This life-cycle will probably reflect part of controller’s life-cycle, or, maybe, part of Android View’s life-cycle. During my initial experiments with MVP/MVC in Android a couple of years ago, I tried this approach. It is complicated and ugly. Not only I had to keep in mind the life-cycles of Activity and Fragment, but also this new view’s life-cycle. It also results in much more boilerplate.
      Therefore I decided to keep the views “unaware” of model’s existence, and let controllers manage everything.

      Reply
  3. Hello, I have 2 years+ experience in I.T as a whole, I’ve been moving from one platform to another within these few years but I’ve finally decided to stick with Android Development, is MVP gonna be the trend in the long run because I’m a really slow learner.

    Reply
    • Hi,
      MVP is already not that trendy. Today MVVM is the “new shiny thing”. However, if you really want to learn something once and avoid re-learning stuff every two years, then chasing the latest trends isn’t a good strategy IMHO.
      I, personally, have been using the pattern described here and in my Architecture course for the past ~4 years and didn’t have to change almost anything about my practices. It’s the best pattern for Android devs as far as I’m concerned and it will remain so in the foreseeable future.
      Regards

      Reply
      • Thank you so much for this. Personally, I was very skeptical whether I should go for MVVM or MVP for the long run. Your reply clears up most of the doubts I had. Thank you!

        Reply
  4. Thanks a lot for such a deep, detailed and clear explanation. But I have a question, I’ve watched your DI course with Dagger on Android And Android Architecture Master Class course on Udemy, but my question is should we use MVC pattern or MVVM, as it is suggested by google and there are basic components that support this pattern. Please answer your Architecture pattern guide for android in context of MVVM. Thanks a lot. You are a great and experiences teacher by the way.

    Reply
    • Hey,
      I, personally, use MVC in all my projects and recommend clients to do the same. However, what you said about MVVM being officially recommended is an important consideration for many projects.
      In my opinion, what you learned in Architecture Course is the best approach to develop Android apps, but you should definitely discuss it with your team.
      Regards
      Vasiliy

      Reply
  5. One of the best article that i read about android architecture. Thanks for taking time to write these articles. I am signing up for your udemy courses on Android architecture, design pattern and multithreading.
    In the last comment you said, “I, personally, use MVC in all my projects and recommend clients to do the same.” – Did you mean MVP? In the article you recommended MVP, hence the confusion.

    Reply
    • Hey Madhan,
      Glad you liked the article. In part 2 I explain why MVC and MVP are pretty much the same architectures, so when I say “I use MVC”, I could also say “I use MVP”.
      However, since this article had been written, I realized that I got lucky by naming it MVC. There is one very distinctive feature to this architecture (namely, Activiy/Fragment as controller) which differentiates it from all other popular approaches. Therefore, having a different name helps here a bit.
      BTW, if you’re going to take my architecture course, then you don’t need to read the rest of this series. That course covers this topic in much more details with better examples.

      Reply

Leave a Comment