MVC / MVP / MVVM

Three ways to keep the user interface apart from the domain logic. Know who talks to whom in each, why the differences matter for testing, and which one a given platform pushes you toward.

Overview

Every screen has the same three jobs: hold the data, draw it, and react when the user does something. MVC, MVP and MVVM are three answers to one question: which object does each job, and who is allowed to talk to whom. Get that right and the domain logic can be tested without a screen, the screen can be redrawn without touching the logic, and two people can work on the two halves at once.

The three patterns are a family, and interviewers like to hear the lineage. MVC came first: Trygve Reenskaug designed it at Xerox PARC in 1978 and 1979, for Smalltalk. MVP grew out of work at IBM and Taligent in the 1990s; Martin Fowler later split it into two variants, Supervising Controller and Passive View (2006). MVVM was named by John Gossman at Microsoft in 2005 for WPF, which relies on data binding; Fowler notes it is the same idea as his Presentation Model (2004) under a different name.

A strong answer names the three parts, draws the arrows, and then says the one thing that separates the patterns: how the view gets updated. In MVC the view watches the model. In MVP the presenter pushes into a passive view. In MVVM a binding layer copies view-model state into the widgets.

The problem all three solve

Without any separation, one class does everything. The user acts on a single screen class that handles input, holds the business rules, draws the widgets and reads and writes the data itself. That class cannot be unit-tested, because every test needs a real window, and any change to the layout risks the business rules. Nothing in it can be tested or changed alone.

The three patterns split that class along the same three jobs.

  • Hold the data and the rules: for example, the account balance and the rule that it cannot go negative. All three patterns call this the Model.
  • Draw it: widgets, HTML, layout and colors. All three call this the View.
  • React to the user: turn a click into a call on the model, then get the screen updated. This is the Controller in MVC, the Presenter in MVP and the ViewModel in MVVM.

The Model is the same in every pattern: domain objects that know nothing about the screen. The differences are all in the third box and in the arrows around it.

Interview questions

  • Walk me through a button click in MVC, MVP and MVVM.
  • Why is MVP easier to unit-test than classic MVC?
  • What does data binding change in MVVM, and what does it cost?
  • What is a fat controller, and how do you fix it?
  • Do Rails, Django and Spring MVC really implement MVC?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio