Model-View-Controller (MVC) Architecture
The MVC ModelHaphazard design can be tolerated on small projects but as code size increases beyond a few hundred lines, particular attention needs to be paid to how the code is structured. Consider the two approaches, below. In the first approach, all the software entities (A,B,C,D) talk to one another. In graph theory, we would call this a complete graph. In the approach shown on the right, the number of high level entities is fewer. Meanwhile, communications is also more restricted, with only one entity (C) having links to the others.
As code size increases, the approach shown on the left will become increasingly more problematic because the programmers who own each of these entities will be forced to build interfaces to most other entities in the system. Meanwhile, debugging will become more difficult as execution flow will bounce from one object to another in an unpredictable pattern. To avoid these pitfalls, there are many different approaches to building a modern, software architecture. In this course, we will describe one popular approach known as Model-View-Controller (MVC). The three most important features of this architecture are:
- The Model and View are separate and distinct software entities. While the View describes what the user sees, the Model typically uses a different set of data (with different datatypes than the Model) to represent what the computer sees;
- The Model and View classes do not directly communicate with each other - they use the Controller entity as a go-between;
- The Model, View, and Controller are the only highest-level entities. Each has strict rules about what functionality it can perform.
We will now describe this approach in more detail.
The MVC ModelMVC ArchitectureThe MVC architectural model for large software applications is one of many popular, modern architectural approaches used in the real world today. It is also the one most favored by Apple. Less important than the particular architectural approach taken is that one is used at all. Generally speaking, a good architectural model can dramatically reduce both code size as well as app complexity. Content from this section is taken mostly from a larger article on MVC architecture which can be found here.
An MVC Architecture for Tic-Tac-ToeNow consider what a Tic-Tac-Toe app might look like if implemented using an MVC approach:
Although the image, above, does not show the code in the View and Model classes, the main point to understand is how the View and the Model are different. While the user sees X's, O's, and blanks, the computer sees -1, 1 and 0.