The MVC Pattern

In this lesson, we will learn about the MVC pattern in detail and how to split the functionalities of our application among several controllers.

Separation of concerns with the MVC pattern

The MVC pattern was conceived to split also the Presentation Layer into two sub-layers. The MVC pattern is specific to web applications. The Presentation Layer of desktop and mobile applications can be split into sublayers using a pattern that is slightly different called MVVM (Model-View-ViewModel).

The Presentation Layer performs the following two tasks:

  1. Handling the interaction pattern between the software and the user. This includes encoding the pattern of communication (how requests and responses evolve), validating user inputs, understanding which Business Layer procedures to invoke, and organizing the response data for a suitable presentation to the user.

  2. Building an adequate graphic for each screen, that is, building adequate HTML and using adequate CSS.

The basic idea of the MVC pattern is to make the task at point 1 completely independent from the one at point 2. That is, to make the logical part of the user-machine interaction independent from the way the whole graphic is implemented. This way we can modify the graphics completely without affecting the way the software is run.

This is important for the following reasons:

  1. Graphic changes are frequent, and the above separation enables us to change the graphics without challenging the stability of the code.

  2. Graphic is better implemented by a different professional role, the web graphic designer, and the separation of concerns between graphics and logic allows an efficacious splitting of the job between developers and graphic designers.

  3. Performing exhaustive testing of the whole web page is very expensive and often the lifetime of the HTML graphic part is too short to justify the cost of building exhaustive tests. Separation of concerns makes the so-called partial tests, which act just on the logical part without interacting with the page HTML, more effective. Such tests are cheaper than complete tests. Instead of using all complete tests, we can implement most of the tests as partial tests on the logical part, and leave just a few complete tests.

Separation of concerns is achieved by using classes called ViewModels as interfaces between all the logical tasks and the HTML building tasks.

The logical part is executed by a processor called Controller while the HTML building is performed by another processor called View. The controller performs all logical tasks of the user-machine interaction and outputs an object called a ViewModel. The ViewModel contains all the data to show the user and the View uses this data to build adequate HTML:

Get hands-on with 1200+ tech skills courses.