LESSON 8.4
MVC, MVVM and layered architecture
Separate presentation, application orchestration, and core business domain logic with architectural patterns: MVC, MVVM, and clean 3-tier layering.
6 min read
When applications grow organically, code often clumps into massive UI files or database scripts: SQL queries inside React components, HTTP session parsing inside domain calculations, and presentation formatting inside database triggers. Any change to the database breaks the frontend, and any change to the UI breaks domain logic.
The problem
// Tangled layers: presentation, domain, and database all in one file
function handleButtonClick(req, res) {
// 1. Presentation & HTTP parsing
const { userId, amount } = req.body;
// 2. Database access
const user = db.query("SELECT * FROM users WHERE id = ?", [userId]);
// 3. Domain business logic
if (user.balance < amount) return res.send("No funds");
user.balance -= amount;
// 4. Persistence
db.query("UPDATE users SET balance = ?", [user.balance]);
// 5. HTML presentation formatting
res.send(`<h1>Success! New balance: $${user.balance}</h1>`);
}The pattern
Layered Architecture divides an application into concentric boundaries:
- Domain Layer: Pure business entities and rules. No external dependencies.
- Application / Use Case Layer: Orchestrates domain entities to achieve specific use cases (e.g.
TransferFundsUseCase). - Infrastructure Layer: Implements technical details (Database, Mailers, HTTP clients).
- Presentation Layer (MVC/MVVM): Handles user interaction, rendering, and input parsing.
In code
When to use it, and when not to
Use Layered Architecture when:
- You are developing medium-to-large business applications that will evolve over years.
- Different teams work on the frontend, business rules, and database schema.
- You want to replace your database driver, web framework, or UI library without rewriting business rules.
Don't use Layered Architecture when:
- You are building a 2-day prototype, CLI script, or simple CRUD tool: strict layering adds unnecessary files and mapping boilerplate.
Where you have already seen it
Every major web framework enforces layering: Nest.js separates Controllers, Services, and Repositories; Spring Boot standardizes @RestController -> @Service -> @Repository; Clean Architecture (Uncle Bob) and Hexagonal Architecture (Ports and Adapters) are formalized evolutions of this layered principle.
Related patterns
- Layered Architecture vs Facade: An Application Service often acts as a Facade over several domain entities and infrastructure services.
- MVC vs MVVM: MVC is typically request-driven (traditional web apps). MVVM is data-binding-driven (modern reactive frontend single-page apps).
Try it
Library Management LLD
Structure a library management system into separated Domain entities, Use Case services, and Storage repositories.