Model View Controller (MVC)

Overview

MVC is a way to sturcture your applications into components that handle specific aspects of an application. This is similar to clean code principles where a function should do one thing. It would be a mess designing a class that handles both the database of your application as well as the visuals.

Model

  • Handles data logic: validating, updating, saving, deleting data.

View

  • Handles visualization of the application to the user.

Controller

  • Handles user requests.

MVC Structures

No Connection Between Model and View

In this version of MVC, there exists no communication between the model and the view. The controller is the middleman between the model and the view. The controller can retrieve data from the model and deliver it to the view for it to be rendered. The controller also handles events from the view and updates the model accordingly.

Below is a simple MVC appplication showcasing the controller as a middleman:

Server Client MVC

When you start to deal with applications in a client-server setting. You may opt for keeping the model and controller on the server side while the view is on the client side. See Below for an example

How To Handle Increased Complexity

Overview

Lets say that your view creates windows and those windows can create even more windows. You then have to answer questions like: Should I put all of this view functionality in a single class? How do events in child windows connect to the controller?

Hopefully some of these questions can be answered here.

Class Structure For Multiple Windows

In a simple application, we may be able to get away with placing the model, view, and controller into only 3 classes. However for more complex applications placing all of this functionality whitin only 3 classes makes the classes bloated and difficult to develop / debug.

To keep our classes clean and simple, we look to the concept of Feature Envy. Feature envy is when methods of a class have nothing to do with variables or functions of the class they belong to. If we have the prospect of multiple windows where each window has a different purpose, it may be wise to create a separate controller class and view class for each window (see Stack Overflow discussion).

In a multi window application one view may be responsible for displaying the model state while another view changes the state of the model. To keep up to date with the changes to the model, we could use the observer pattern. Using this pattern, the controller subscribes to the model and the model sends out a notification whenever it is updated.

Note

If keeping a view up to date with the model not a high priority you could instead update the view at regular intervals.

Below is a MVC application that handles multiple controllers, multiple views, and a model that handles update events: