Design Patterns 101: Making Sense Of The MVC Pattern
Imagine this–you’ve come up with a great idea for an app, and you just can’t wait to build it! You could sit down at your computer and just start typing, and create your classes and user interface as you go… but that’s a good way to create a mess. If you don’t make a plan to organize your code, you’ll end up with something that’s really hard to read, hard to maintain, and hard to test. That’s where the MVC design pattern comes in–it’s like having a ready-made plan for how to build an application. Making sense of the MVC pattern is a pretty critical step on any junior developer’s journey to creating full software applications–it can be difficult to get your head around at first, but once you ‘get it’, you’ll often find yourself reaching for it when building web-based applications.
Welcome to the first entry in “Design Patterns 101”, a series of articles where I’ll walk you through a particular design pattern and why it’s used!
What is a design pattern?
A design pattern is a little like a recipe for solving a common problem in software development. When you’re cooking dinner, you might follow a recipe to make a certain dish and make sure that it comes out tasting okay. In programming, following a design pattern to solve a specific problem makes sure that the solution is completed in a way that has been proven to be effective. Design patterns are guides that have been made and shared by experienced developers to save time and energy when solving a common problem.
What is the MVC pattern?
The “MVC” acronym stands for “Model-View Controller”. MVC is an architectural pattern–a way to organize code in a software application.
The model represents the data and business logic in your application. It’s where you store and manage the information that your program needs to work with. Model classes are just that–classes–that create the objects to hold the data and logic your application uses.
The view is the part of your application that an end user interacts with. It can be a graphical user interface (GUI), or just the data that is returned from your application (if you are building something like an API that only returns data, not a traditional “view”). View classes or files usually don’t do much more than displaying information and/or taking user input; business logic belongs in the model classes.
The controller transfers information between the model and the view. It can take user input from the view, make decisions based on that input, and update the model accordingly. Controller classes, in a web application, handle the HTTP request-response process between the two other parts of the application (the view, and the model).
For example…
If we were using Java to make a web application about cats, we may include a model class to represent the data for a fun fact about cats:
public class CatFact {
private int catFactId;
private String catFactText;
public CatFact(int id, String text) {
this.catFactId = id;
this.catFactText = text;
}
public String getCatFactText() {
return catFactText;
}
//other getters & setters omitted for brevity
}
We also could include a Spring Boot controller class to respond to HTTP requests for cat facts, with an appropriate endpoint, “/random”, to return a random cat fact:
@RestController
@RequestMapping("/catfact")
public class CatFactController {
@GetMapping("/random")
public CatFact getRandomCatFact() {
//retrieving a cat fact from the data store
CatFact randomFact = dataAccess.getRandomCatFact();
//return the cat fact to the view
return randomFact;
}
}
Finally, the view could be a website or other GUI displaying the cat fact, or it could be the data itself, returned to whatever client is being used to view the cat fact data:
{
"id": 238,
"text": "An orange tabby cat named Stubbs was the mayor of Talkeetna, Alaska for 20 years. Stubbs won several uncontested elections, and although he didn't hold any actual legislative power, he was a beloved local figure."
}
Where did the MVC pattern come from?
Trygve Reenskaug first created the MVC pattern while working at the Xerox Palo Alto Research Center (PARC) in the 1970s. He wanted a pattern that could be used to structure any program where users interact with a large, complex data set, although his original design was a little bit different from the MVC pattern today. The current form of MVC comes from a 1988 article by two ex-PARC employees, where the pattern was presented as a general “programming paradigm and methodology”. (For more information, visit the Model-View-Controller article on Wikipedia)
Although it was originally designed for desktop applications, MVC became a common pattern used for architecting web-based solutions. In his book “Patterns of Enterprise Application Architecture”, Martin Fowler presented MVC as a pattern where an “input controller” receives a request, sends the appropriate messages to a model object, takes a response from the model object, and passes the response to the appropriate view for display–which is the approach that most web-based implementations of the MVC pattern use today, including the Spring framework for Java, the ASP.NET MVC framework, and the Ruby on Rails framework.
Why use the MVC pattern?
The MVC pattern is useful because it enforces a clear separation of concerns. Models handle data and business logic, views show information to the user, and controllers orchestrate the transfer of information between the two. Having these three areas with different purposes and responsibilities can make the project easier to maintain and ensure the codebase is readily testable.
Also, because the three components of the pattern are meant to be separate components, you can often reuse a model, view, or controller in several parts of the same application, or even across different applications. For example, if you had two different websites that dealt with the same data, you could potentially use at least some of the same controllers and models between the two sites, even if the views shown to the user were different.
The MVC pattern has also been around for awhile, and it is considered a well-known and widely-accepted way of doing things. Using it to organize your application means that other developers will know where to look in the codebase for files that fit into one of the three domains, and encourages following good practices regarding separation of concerns, code encapsulation, and writing DRY (Don’t Repeat Yourself) code.
Conclusion
From its origins at Xerox PARC to widespread adoption for web application development, the MVC pattern has become a mainstay for writing robust, maintainable, scalable applications. Using the Model-View-Controller pattern leads to code that is clean, modular, and well-organized, separating out the concerns of an application’s data and logic, presentation, and user interaction. Once you get the hang of using the MVC pattern to write applications, you’ll find yourself reaching into your programmer’s toolbox and pulling it out to use again and again. Happy coding!