🌐 Web Development

MVC

Model-View-Controller

MVC is a software design pattern that separates an application into Model (data), View (display), and Controller (logic). Separation of concerns improves maintainability and testability, and it is adopted in Ruby on Rails, Django, Spring, and others.

πŸ“– Detailed Explanation

MVC (Model-View-Controller) is a software architecture pattern first introduced by Trygve Reenskaug in Smalltalk in 1979. It separates an application into three core components to achieve Separation of Concerns and improves code reusability and maintainability.

The Model is responsible for the application's data and business logic. It includes interaction with the database, validation, and data processing rules. The View is responsible for the user interface and visually represents the Model's data. HTML, template engines, and front-end components fall into this category.

The Controller acts as an intermediary between the Model and the View. It receives user input, updates the Model, and selects the appropriate View to generate a response. It performs roles such as handling HTTP requests, routing, and checking authentication/authorization. Separating these three components allows each area to be developed and tested independently.

Most modern web frameworks adopt MVC or its variants (MVP, MVVM). Ruby on Rails popularized MVC with "Convention over Configuration," and Django (MTV: Model-Template-View), ASP.NET MVC, Spring MVC, and others are widely used. Front-end frameworks such as React and Vue focus on the View layer and handle part of MVC within the overall architecture.

πŸ’» Code Example

// Express.js + TypeScript둜 κ΅¬ν˜„ν•œ MVC νŒ¨ν„΄ 예제

// ========== Model (models/User.ts) ==========
interface User {
  id: number;
  name: string;
  email: string;
  createdAt: Date;
}

class UserModel {
  private users: User[] = [];
  private nextId = 1;

  async findAll(): Promise<User[]> {
    return this.users;
  }

  async findById(id: number): Promise<User | undefined> {
    return this.users.find(user => user.id === id);
  }

  async create(data: Omit<User, 'id' | 'createdAt'>): Promise<User> {
    const user: User = {
      id: this.nextId++,
      ...data,
      createdAt: new Date()
    };
    this.users.push(user);
    return user;
  }

  async update(id: number, data: Partial<User>): Promise<User | null> {
    const index = this.users.findIndex(u => u.id === id);
    if (index === -1) return null;
    this.users[index] = { ...this.users[index], ...data };
    return this.users[index];
  }

  async delete(id: number): Promise<boolean> {
    const index = this.users.findIndex(u => u.id === id);
    if (index === -1) return false;
    this.users.splice(index, 1);
    return true;
  }
}

// ========== Controller (controllers/UserController.ts) ==========
import { Request, Response } from 'express';

class UserController {
  constructor(private userModel: UserModel) {}

  async index(req: Request, res: Response) {
    try {
      const users = await this.userModel.findAll();
      res.json({ success: true, data: users });
    } catch (error) {
      res.status(500).json({ success: false, error: 'Server error' });
    }
  }

  async show(req: Request, res: Response) {
    const id = parseInt(req.params.id);
    const user = await this.userModel.findById(id);

    if (!user) {
      return res.status(404).json({ success: false, error: 'User not found' });
    }
    res.json({ success: true, data: user });
  }

  async create(req: Request, res: Response) {
    const { name, email } = req.body;

    if (!name || !email) {
      return res.status(400).json({ success: false, error: 'Name and email required' });
    }

    const user = await this.userModel.create({ name, email });
    res.status(201).json({ success: true, data: user });
  }

  async update(req: Request, res: Response) {
    const id = parseInt(req.params.id);
    const user = await this.userModel.update(id, req.body);

    if (!user) {
      return res.status(404).json({ success: false, error: 'User not found' });
    }
    res.json({ success: true, data: user });
  }

  async delete(req: Request, res: Response) {
    const id = parseInt(req.params.id);
    const deleted = await this.userModel.delete(id);

    if (!deleted) {
      return res.status(404).json({ success: false, error: 'User not found' });
    }
    res.status(204).send();
  }
}

// ========== Router (routes/users.ts) ==========
import { Router } from 'express';

const router = Router();
const userModel = new UserModel();
const userController = new UserController(userModel);

router.get('/', (req, res) => userController.index(req, res));
router.get('/:id', (req, res) => userController.show(req, res));
router.post('/', (req, res) => userController.create(req, res));
router.put('/:id', (req, res) => userController.update(req, res));
router.delete('/:id', (req, res) => userController.delete(req, res));

export default router;

πŸ—£οΈ Examples of Practical Conversations

πŸ’¬ Situation: New project architecture design meeting

PM "How are we going to structure the backend for the new project? I'd like a structure that team members can easily understand and collaborate on."
Backend "We plan to use the MVC pattern as the base, but add a Service layer to keep the Controller thin. The structure is: the Controller handles only requests and responses, business logic goes in the Service, and data access goes in the Model/Repository."
Frontend "So we just communicate with the REST API from the front end, right? Since we'll use React for the View layer, it seems the backend only needs to return JSON."
Backend "Right. Whereas in traditional MVC the View was a template engine, in our case the API response plays the role of the View, and React handles the actual screen. This structure is sometimes called an MVC + SPA architecture. It also becomes easier to write unit tests for each layer."

⚠️ Cautions

πŸ”— Related Terms

πŸ”₯ Real-World Incidents

Twitter (X) 2013

Performance degradation and scaling failure caused by a Fat Controller

Cause: Business logic was concentrated in the Controller in the early Ruby on Rails-based MVC

Impact: The "Fail Whale" error page was shown frequently, and the service went down during large-scale events

Solution: Complete rewrite as Scala-based microservices, introduction of a Service layer

Lesson: MVC alone has difficulty handling large-scale traffic; keeping the Controller thin and separating the Service is essential

General Case Common

Unmaintainability caused by a God Object Model

Cause: A single Model class contained data access, business logic, and validation all together

Impact: Model files thousands of lines long, entire test suite failing on small changes, failure to onboard new developers

Solution: Separate data access with the Repository pattern, separate Domain objects and Entities

Lesson: Adhere to the Single Responsibility Principle (SRP) and clearly define the role of each component

πŸ“ Comprehension Quiz

Q1. What is the role of the Controller in MVC?

Q2. What is the problem with the "Fat Controller" anti-pattern?

Q3. In Django's MTV pattern, which MVC component does the View correspond to?

πŸ“š Learn More

πŸ’¬ Questions & Contributions

If this page has any errors or you would like to add something, please let us know!