The Model-View-Controller: Why It Matters
Tags: mvc, beginners, architecture
Published: 2022-06-06 02:26:47

Remember when you first began learning to code, and your codebase was possibly hundreds or even thousands of lines long, all contained within a single script file? What was your debugging experience like as a result? If you cringe at the thought of those early days, it’s time to discuss an organized, more efficient way of managing your codebase through the software pattern known as the Model-View-Controller or MVC, a long-held philosophy common in software engineering. 

**The Model**

The Model stores and represents data. It can be contained as a single object or a series of objects. These objects are transferred back and forth between the View and the Controller with the latter handling what gets presented at the View level or user interface. The Model also supports code reusability (more on that later), whereby data that gets returned by the Model displays without applying any formatting. This means one single Model can display a variety of interfaces, thus reducing the need for code duplication.  

```
const { Model, DataTypes } = require("sequelize");
const sequelize = require("../config/connection");

class Project extends Model {}

Project.init(
  {
    id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
    },
```

**The View**

The View represents the graphical user interface or GUI. It is the client-facing side of an application in which direct user interaction takes place. You can think of the View as responding to a user event such as a button click. Anytime a user clicks a ‘submit’ button or inputs text into a field, they are doing so via the View. Generally, your HTML or other template engine source lives within the View component. This component serves as the final output to the client and is ultimately responsible for what the user sees.

```
<div class="text-center">
  <h2>{{name}}</h2>
  <p>{{{get_emoji}}}</p>
  <p>{{description}}</p>
  <p>Created by {{user.name}} on {{format_date date_created}}</p>
  <p>
    <span for="img" aria-label="money">💲</span>
    <span class="dollar-amount">{{format_amount needed_funding}}</span>
    needed
  </p>
  <p>
    <button class="btn btn-primary">GoFund Me</button>
  </p>
</div>
```

**The Controller**

The Controller acts as an intermediary between the View and the Model. It is responsible for handling data requests. Creating, Reading, Updating and Deleting data based on user input is fundamental in the Controller. It will read and retrieve data from the Model, then return data to the client or View for visibility to a user. If you are familiar with developing CRUD applications, the Controller will make logical sense to you. 

```
const router = require("express").Router();
const { Project } = require("../../models");
const withAuth = require('../../utils/auth');

router.post("/", async (req, res) => {
  try {
    const newProject = await Project.create({
      ...req.body,
      user_id: req.session.user_id,
    });

    res.status(200).json(newProject);
  } catch (err) {
    res.status(400).json(err);
  }
});
```
**Separation of Concerns**

Throughout your learning journey, you may have encountered terms such as _encapsulation_ _of information_ or _modularity_. Such terms are closely tied to the principle of Separation of Concerns or SoC. Separation of Concerns are based on a popular architectural paradigm whereby an application is isolated into an individual component or module, each responsible for its own functionality and purpose. Interaction between modules is often apparent, yet modules are still independent of each other. 

The philosophy within the Separation of Concerns also includes the reduction of _coupling_, the degree of interdependence of software modules, and the increase of _cohesion_, the degree to which the elements inside a module belong together. The relationship between modules through coupling and cohesion promotes what is known as good programming practices according to the book _Structured Design_ (1979).

**Benefits of MVC Architecture**

There are numerous benefits to the MVC architecture. If you’ve ever collaborated within a team of developers, designers, or engineers, you’re likely aware of just how critical the planning phase is in web development. Having a development process in place, especially in the early stages of application development, helps to ensure ongoing maintenance and scalability. 

The MVC helps to simplify the development process by promoting an agile workflow, thus increasing the speed of the development process. One developer might create the application logic of an application and focus solely on the Controller, while another devotes efforts to the user interface. 

The MVC architecture supports test-driven development or TDD. Debugging and testing are all part of the development process. By separating an application into individual components makes the debugging and testing experience smoother. As your application scales, complexity naturally grows, but the MVC method supports this through decomposition. 

Code reusability is another benefit of the MVC. Because data stored within the Model is completely isolated from the View, the View can determine a variety of ways for data to be displayed, all the while using the same Model. Code reusability also enforces the CI/CD method. 

**Important Considerations When Implementing MVC**

The Model-View-Controller requires careful consideration of the entire life cycle of an application, in advance of the build-production stage. This means identifying how an application functions and interacts. An upfront analysis will ensure you create the appropriate layout architecture for your application. For smaller applications, the MVC approach may be too much, so consider this before implementing. 

**Summary**

The Model-View-Controller architecture pattern is well-established architecture paradigm designed to separate application logic using three isolated components. The Separation of Concerns principle advocates for the adoption of the MVC. Its primary benefit is the ability to manage an application with ease through independent responsibility and function. When done correctly, the MVC increases faster development. Adopting an MVC architecture pattern in the early stages of development helps to ensure long-term application structure and supports scalability as your application grows.