Patterncore
Model-view-controller
Also called MVC, Model View Controller.
MVC splits an interactive program into a model that holds the data and the rules, views that present the model, and controllers that turn user input into requests to the model.
- Family
- architectural
- Intent
- Splits user interface interaction into three distinct roles.
- Also called
- Models-Views-Controllers
Intent
Splits user interface interaction into three distinct roles.4 The model holds the data and the rules of the problem. A view presents the model to the user. A controller takes the input of the user and turns it into requests. The model does not know how it is shown or how the user changes it.
Problem
A to-do list program shows a list of items and a line that counts the open and the finished items. The user types commands. The first version keeps the items in the window code. Each command handler changes the list, redraws the list, and recomputes the count.
After a few months the program has a second window with a chart, a command line mode, and a set of tests. The rule "an item is done only once" is in the window code, so the command line mode has a second copy of it. The tests must create a window to test a rule about items. Each command handler must know every window that shows the items, and a handler that forgets one leaves a stale screen.
The forces are these. The rules about items should exist once, in code that has no screen. Several presentations of the same data should stay consistent. The code that reads input should not also format output. And a person should be able to add a presentation without a change to the rules.
Solution
Reenskaug's note of 1979 gives the three roles.1
- "Models represent knowledge." A model can be one object or a structure of objects. Its parts should correspond to the parts of the problem, not to details of the screen.
- "A view is a (visual) representation of its model." It shows some attributes and hides others, so it acts as "a presentation filter". It gets its data from the model by asking questions in the terms of the model.
- "A controller is the link between a user and the system." It arranges the views on the screen, gives the user menus and other means to give commands, and translates the input of the user into messages.
The note also states two limits. A controller should never supplement the views, and a view should never know about user input such as mouse operations and keystrokes.1
In the Smalltalk-80 framework, the model keeps a list of dependents, and each view registers as a dependent of its model. When the model changes, it sends a changed message, and each dependent gets an update message and asks the model for the data it needs.2 This is the Observer pattern. Fowler calls this use Observer Synchronization: the controller changes the model, and the views follow without the controller knowing which views exist.5
user input
|
v
+------------+ requests +---------+
| Controller | ------------> | Model |
+------------+ +---------+
| ^
"I changed" | | queries
(observer list) v |
+---------+
| View | ---> screen
+---------+
The model knows its views only as observers. It does not import any view class. The arrows from the controller and the view point to the model, and no arrow leaves the model except the notification.
Design Patterns uses Smalltalk MVC in its first chapter to show patterns that work together. The subscribe and notify protocol between a model and its views is Observer. Views can nest, and a composite view contains other views, which is Composite pattern. A view delegates its response to input to a controller object, and a different controller gives a different response, which is Strategy pattern.3
Fowler names the most influential idea of MVC Separated Presentation: a clear division between the domain objects and the presentation objects, where the domain objects do not refer to the presentation.5 The view and controller split matters less. Many toolkits put both roles in one object. Swing collapses the view and the controller of each component into a single UI object, and keeps the model separate. Its documentation calls this a "separable model architecture".9
The web form
Web frameworks use the same three names for a different flow. A request arrives. A router picks a controller method. The controller works with the model, then chooses a view and gives it the data. The view renders HTML. The response goes back, and the request is over.67 No view observes the model, because no view lives longer than one request.
ASP.NET Core states the dependency rule: both the view and the controller depend on the model, and the model depends on neither.6 It also asks for thin controllers: business logic belongs in the model, not in the controller.6
The following program sends six requests to a router in memory. The model has no HTML and no HTTP. The view functions escape the text of the items with html.escape, so a title with markup is shown as text.10
import re
from html import escape
class TodoModel:
def __init__(self) -> None:
self.items: list[dict] = []
def add(self, title: str) -> None:
if not title:
raise ValueError("a title is required")
self.items.append({"title": title, "done": False})
def complete(self, number: int) -> None:
if not 1 <= number <= len(self.items):
raise LookupError(f"no item {number}")
self.items[number - 1]["done"] = True
# Views: data in, HTML out. No input handling, no rules.
def list_page(items: list[dict]) -> str:
rows = "".join(f"<li>{'[x]' if i['done'] else '[ ]'} {escape(i['title'])}</li>" for i in items)
return f"<ul>{rows}</ul>"
def error_page(message: str) -> str:
return f"<p>{escape(message)}</p>"
class TodoController:
def __init__(self, model: TodoModel) -> None:
self.model = model
def index(self, form: dict) -> tuple[int, str]:
return 200, list_page(self.model.items)
def create(self, form: dict) -> tuple[int, str]:
self.model.add(form.get("title", ""))
return 303, "/todos"
def complete(self, form: dict, number: str) -> tuple[int, str]:
try:
self.model.complete(int(number))
except LookupError as err:
return 404, error_page(str(err))
return 303, "/todos"
controller = TodoController(TodoModel())
routes = [
("GET", r"/todos", controller.index),
("POST", r"/todos", controller.create),
("POST", r"/todos/(\d+)/done", controller.complete),
]
def dispatch(method: str, path: str, form: dict) -> tuple[int, str]:
for route_method, pattern, action in routes:
match = re.fullmatch(pattern, path)
if match and method == route_method:
return action(form, *match.groups())
return 404, error_page(f"no route for {method} {path}")
requests = [
("POST", "/todos", {"title": "buy milk"}),
("POST", "/todos", {"title": "<b>tea</b>"}),
("POST", "/todos/1/done", {}),
("POST", "/todos/7/done", {}),
("GET", "/todos", {}),
("GET", "/admin", {}),
]
for method, path, form in requests:
status, body = dispatch(method, path, form)
print(f"{method} {path} -> {status} {body}")
POST /todos -> 303 /todos
POST /todos -> 303 /todos
POST /todos/1/done -> 303 /todos
POST /todos/7/done -> 404 <p>no item 7</p>
GET /todos -> 200 <ul><li>[x] buy milk</li><li>[ ] <b>tea</b></li></ul>
GET /admin -> 404 <p>no route for GET /admin</p>
The controller answers a POST with a redirect, status 303, instead of a page. The browser then sends a GET for the list. The controller methods stay small: each one reads the request, calls the model once, and picks a response. The escaping is in the view, because only the view knows that the output is HTML. See Cross-site scripting.
Django uses other names for the same parts. A Django "view" is the Python function for a URL, and it decides which data is presented. A template decides how the data is presented. The Django FAQ says that the controller is "probably the framework itself", the machinery that sends a request to the view for its URL, and suggests the name "MTV", for model, template and view.8
Example
Each example file builds the to-do program of the problem section in the classic form. A TodoModel holds the items and a list of observers. A list view and a summary view subscribe to the model. A controller reads five command lines, prints each one, and calls add or complete on the model. The model then tells both views, and each view prints its part. The controller prints the errors that the model reports, and it rejects a line that it cannot read.
The views never receive a call from the controller. When the controller adds an item, the list and the summary update because they observe the model. All eight programs print the same output. The notes in each file show how the language holds the observer list: a list of callables in Python, an EventTarget in JavaScript, an event in C#, a slice of functions in Go, std::function in C++, and boxed closures that receive a slice in Rust.
from collections.abc import Callable
from dataclasses import dataclass
@dataclass
class Item:
title: str
done: bool = False
class TodoModel:
"""Knows the items and the rules. Knows nothing about screens or input."""
def __init__(self) -> None:
self._items: list[Item] = []
self._observers: list[Callable[[], None]] = []
def subscribe(self, observer: Callable[[], None]) -> None:
self._observers.append(observer)
def items(self) -> list[Item]:
return list(self._items)
def add(self, title: str) -> None:
if not title:
raise ValueError("a title is required")
self._items.append(Item(title))
self._changed()
def complete(self, number: int) -> None:
if not 1 <= number <= len(self._items):
raise ValueError(f"no item {number}")
self._items[number - 1].done = True
self._changed()
def _changed(self) -> None:
for observer in self._observers:
observer()
class ListView:
"""Shows every item. Asks the model for data when the model changes."""
def __init__(self, model: TodoModel) -> None:
self._model = model
model.subscribe(self.render)
def render(self) -> None:
for n, item in enumerate(self._model.items(), 1):
print(f" [{'x' if item.done else ' '}] {n} {item.title}")
class SummaryView:
"""A second view of the same model."""
def __init__(self, model: TodoModel) -> None:
self._model = model
model.subscribe(self.render)
def render(self) -> None:
items = self._model.items()
done = sum(item.done for item in items)
print(f" summary: {len(items) - done} open, {done} done")
class Controller:
"""Turns user input into calls on the model. Shows input errors."""
def __init__(self, model: TodoModel) -> None:
self._model = model
def handle(self, line: str) -> None:
print(f"> {line}")
command, _, argument = line.partition(" ")
try:
if command == "add":
self._model.add(argument)
elif command == "done" and argument.isdigit():
self._model.complete(int(argument))
else:
print(f" error: cannot read {line!r}")
except ValueError as err:
print(f" error: {err}")
model = TodoModel()
ListView(model)
SummaryView(model)
controller = Controller(model)
for line in ["add buy milk", "add write report", "done 1", "done 7", "rename 2"]:
controller.handle(line)
> add buy milk
[ ] 1 buy milk
summary: 1 open, 0 done
> add write report
[ ] 1 buy milk
[ ] 2 write report
summary: 2 open, 0 done
> done 1
[x] 1 buy milk
[ ] 2 write report
summary: 1 open, 1 done
> done 7
error: no item 7
> rename 2
error: cannot read 'rename 2'
- Verdict: idiom. Python has no construct for the pattern. Three classes and a list of callbacks give the classic form.
- The model calls its observers with no arguments. Each view then asks the model for the data it shows, so the model does not know what a view needs.
- The controller never prints the list. It changes the model, and the change reaches both views through the observers. Errors in the input are the controller's to report.
- The input is a fixed list of lines, so the program runs without a person at a terminal. A loop over
sys.stdinwould make it interactive and change nothing else.
#include <algorithm>
#include <functional>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
struct Item {
std::string title;
bool done = false;
};
class TodoModel {
public:
void subscribe(std::function<void()> f) { observers_.push_back(std::move(f)); }
const std::vector<Item>& items() const { return items_; }
void add(const std::string& title) {
if (title.empty()) throw std::invalid_argument("a title is required");
items_.push_back({title});
changed();
}
void complete(int n) {
if (n < 1 || n > static_cast<int>(items_.size()))
throw std::invalid_argument("no item " + std::to_string(n));
items_[n - 1].done = true;
changed();
}
private:
void changed() const {
for (const auto& f : observers_) f();
}
std::vector<Item> items_;
std::vector<std::function<void()>> observers_;
};
class ListView {
public:
explicit ListView(TodoModel& model) {
model.subscribe([&model] {
int n = 1;
for (const auto& item : model.items())
std::cout << " [" << (item.done ? 'x' : ' ') << "] " << n++ << " " << item.title << "\n";
});
}
};
class SummaryView {
public:
explicit SummaryView(TodoModel& model) {
model.subscribe([&model] {
const auto& items = model.items();
auto done = std::count_if(items.begin(), items.end(), [](const Item& i) { return i.done; });
std::cout << " summary: " << items.size() - done << " open, " << done << " done\n";
});
}
};
class Controller {
public:
explicit Controller(TodoModel& model) : model_(model) {}
void handle(const std::string& line) {
std::cout << "> " << line << "\n";
auto space = line.find(' ');
std::string command = line.substr(0, space);
std::string argument = space == std::string::npos ? "" : line.substr(space + 1);
bool number = !argument.empty() && std::all_of(argument.begin(), argument.end(), ::isdigit);
try {
if (command == "add") model_.add(argument);
else if (command == "done" && number) model_.complete(std::stoi(argument));
else std::cout << " error: cannot read '" << line << "'\n";
} catch (const std::invalid_argument& err) {
std::cout << " error: " << err.what() << "\n";
}
}
private:
TodoModel& model_;
};
int main() {
TodoModel model;
ListView list(model);
SummaryView summary(model);
Controller controller(model);
for (const char* line : {"add buy milk", "add write report", "done 1", "done 7", "rename 2"})
controller.handle(line);
}
> add buy milk
[ ] 1 buy milk
summary: 1 open, 0 done
> add write report
[ ] 1 buy milk
[ ] 2 write report
summary: 2 open, 0 done
> done 1
[x] 1 buy milk
[ ] 2 write report
summary: 1 open, 1 done
> done 7
error: no item 7
> rename 2
error: cannot read 'rename 2'
- Verdict: idiom.
std::function<void()>holds each observer. The views subscribe lambdas that capture the model by reference. items()returns aconstreference, so a view reads the vector without a copy and cannot change it.- The lambdas hold references to the model, so the model must outlive the views' subscriptions. Here all objects live in
main, and the model is created first.
import java.util.ArrayList;
import java.util.List;
public class Main {
record Item(String title, boolean done) {}
static final class TodoModel {
private final List<Item> items = new ArrayList<>();
private final List<Runnable> observers = new ArrayList<>();
void subscribe(Runnable observer) { observers.add(observer); }
List<Item> items() { return List.copyOf(items); }
void add(String title) {
if (title.isEmpty()) throw new IllegalArgumentException("a title is required");
items.add(new Item(title, false));
changed();
}
void complete(int number) {
if (number < 1 || number > items.size()) throw new IllegalArgumentException("no item " + number);
items.set(number - 1, new Item(items.get(number - 1).title(), true));
changed();
}
private void changed() { observers.forEach(Runnable::run); }
}
static final class ListView {
ListView(TodoModel model) {
model.subscribe(() -> {
List<Item> items = model.items();
for (int i = 0; i < items.size(); i++) {
Item item = items.get(i);
System.out.println(" [" + (item.done() ? "x" : " ") + "] " + (i + 1) + " " + item.title());
}
});
}
}
static final class SummaryView {
SummaryView(TodoModel model) {
model.subscribe(() -> {
List<Item> items = model.items();
long done = items.stream().filter(Item::done).count();
System.out.println(" summary: " + (items.size() - done) + " open, " + done + " done");
});
}
}
static final class Controller {
private final TodoModel model;
Controller(TodoModel model) { this.model = model; }
void handle(String line) {
System.out.println("> " + line);
String[] parts = line.split(" ", 2);
String argument = parts.length > 1 ? parts[1] : "";
try {
if (parts[0].equals("add")) model.add(argument);
else if (parts[0].equals("done") && argument.matches("\\d+")) model.complete(Integer.parseInt(argument));
else System.out.println(" error: cannot read '" + line + "'");
} catch (IllegalArgumentException err) {
System.out.println(" error: " + err.getMessage());
}
}
}
public static void main(String[] args) {
TodoModel model = new TodoModel();
new ListView(model);
new SummaryView(model);
Controller controller = new Controller(model);
for (String line : List.of("add buy milk", "add write report", "done 1", "done 7", "rename 2")) {
controller.handle(line);
}
}
}
> add buy milk
[ ] 1 buy milk
summary: 1 open, 0 done
> add write report
[ ] 1 buy milk
[ ] 2 write report
summary: 2 open, 0 done
> done 1
[x] 1 buy milk
[ ] 2 write report
summary: 1 open, 1 done
> done 7
error: no item 7
> rename 2
error: cannot read 'rename 2'
- Verdict: idiom. Each view subscribes a
Runnableto the model in its constructor. The model holdsRunnables, so it has no dependency on any view class. items()returnsList.copyOf, an unmodifiable copy, so a view cannot change the model.- Swing follows the same split: a
JTableview shows aTableModeland listens for its events. That library is part of the JDK but needs a display, so this program uses text.
var model = new TodoModel();
model.Changed += () =>
{
var items = model.Items;
for (var i = 0; i < items.Count; i++)
Console.WriteLine($" [{(items[i].Done ? "x" : " ")}] {i + 1} {items[i].Title}");
};
model.Changed += () =>
{
var done = model.Items.Count(item => item.Done);
Console.WriteLine($" summary: {model.Items.Count - done} open, {done} done");
};
var controller = new Controller(model);
foreach (var line in new[] { "add buy milk", "add write report", "done 1", "done 7", "rename 2" })
controller.Handle(line);
record Item(string Title, bool Done = false);
sealed class TodoModel
{
private readonly List<Item> _items = [];
public event Action? Changed;
public IReadOnlyList<Item> Items => _items.AsReadOnly();
public void Add(string title)
{
if (title.Length == 0) throw new ArgumentException("a title is required");
_items.Add(new Item(title));
Changed?.Invoke();
}
public void Complete(int number)
{
if (number < 1 || number > _items.Count) throw new ArgumentException($"no item {number}");
_items[number - 1] = _items[number - 1] with { Done = true };
Changed?.Invoke();
}
}
sealed class Controller(TodoModel model)
{
public void Handle(string line)
{
Console.WriteLine($"> {line}");
var parts = line.Split(' ', 2);
var argument = parts.Length > 1 ? parts[1] : "";
try
{
if (parts[0] == "add") model.Add(argument);
else if (parts[0] == "done" && int.TryParse(argument, out var n)) model.Complete(n);
else Console.WriteLine($" error: cannot read '{line}'");
}
catch (ArgumentException err)
{
Console.WriteLine($" error: {err.Message}");
}
}
}
> add buy milk
[ ] 1 buy milk
summary: 1 open, 0 done
> add write report
[ ] 1 buy milk
[ ] 2 write report
summary: 2 open, 0 done
> done 1
[x] 1 buy milk
[ ] 2 write report
summary: 1 open, 1 done
> done 7
error: no item 7
> rename 2
error: cannot read 'rename 2'
- Verdict: idiom. A C#
eventis the model's observer list, and the views are lambdas that the composition code adds with+=. Itemsreturns a read-only wrapper, so a view can read the list and cannot change it.- ASP.NET Core MVC uses the three names for the web form of the pattern: a controller class handles a request, works with the model, and chooses a view. The node page compares the two forms.
// The model extends EventTarget, so views can listen for "change" events.
class TodoModel extends EventTarget {
#items = [];
items() {
return this.#items.map((item) => ({ ...item }));
}
add(title) {
if (!title) throw new RangeError("a title is required");
this.#items.push({ title, done: false });
this.dispatchEvent(new Event("change"));
}
complete(number) {
if (number < 1 || number > this.#items.length) throw new RangeError(`no item ${number}`);
this.#items[number - 1].done = true;
this.dispatchEvent(new Event("change"));
}
}
function listView(model) {
model.addEventListener("change", () => {
model.items().forEach((item, i) => console.log(` [${item.done ? "x" : " "}] ${i + 1} ${item.title}`));
});
}
function summaryView(model) {
model.addEventListener("change", () => {
const items = model.items();
const done = items.filter((item) => item.done).length;
console.log(` summary: ${items.length - done} open, ${done} done`);
});
}
class Controller {
#model;
constructor(model) { this.#model = model; }
handle(line) {
console.log(`> ${line}`);
const [command, ...rest] = line.split(" ");
const argument = rest.join(" ");
try {
if (command === "add") this.#model.add(argument);
else if (command === "done" && /^\d+$/.test(argument)) this.#model.complete(Number(argument));
else console.log(` error: cannot read '${line}'`);
} catch (err) {
if (!(err instanceof RangeError)) throw err;
console.log(` error: ${err.message}`);
}
}
}
const model = new TodoModel();
listView(model);
summaryView(model);
const controller = new Controller(model);
for (const line of ["add buy milk", "add write report", "done 1", "done 7", "rename 2"]) controller.handle(line);
> add buy milk
[ ] 1 buy milk
summary: 1 open, 0 done
> add write report
[ ] 1 buy milk
[ ] 2 write report
summary: 2 open, 0 done
> done 1
[x] 1 buy milk
[ ] 2 write report
summary: 1 open, 1 done
> done 7
error: no item 7
> rename 2
error: cannot read 'rename 2'
- Verdict: idiom.
EventTargetis part of the platform in browsers and in Node, so the model gets its observer list from the runtime. - In a browser, the views would write to the DOM, and the controller would be the event handlers of the form. The three roles stay the same.
items()returns copies, so a view cannot change the model while it renders.
interface Item {
readonly title: string;
readonly done: boolean;
}
type Listener = () => void;
class TodoModel {
#items: Item[] = [];
#listeners: Listener[] = [];
subscribe(listener: Listener): void {
this.#listeners.push(listener);
}
items(): readonly Item[] {
return this.#items;
}
add(title: string): void {
if (title === "") throw new RangeError("a title is required");
this.#items = [...this.#items, { title, done: false }];
this.#changed();
}
complete(number: number): void {
if (number < 1 || number > this.#items.length) throw new RangeError(`no item ${number}`);
this.#items = this.#items.map((item, i) => (i === number - 1 ? { ...item, done: true } : item));
this.#changed();
}
#changed(): void {
this.#listeners.forEach((listener) => listener());
}
}
// A view is a function from the model's data to output.
const renderList = (items: readonly Item[]): string[] =>
items.map((item, i) => ` [${item.done ? "x" : " "}] ${i + 1} ${item.title}`);
const renderSummary = (items: readonly Item[]): string[] => {
const done = items.filter((item) => item.done).length;
return [` summary: ${items.length - done} open, ${done} done`];
};
class Controller {
readonly #model: TodoModel;
constructor(model: TodoModel) {
this.#model = model;
}
handle(line: string): void {
console.log(`> ${line}`);
const space = line.indexOf(" ");
const command = space < 0 ? line : line.slice(0, space);
const argument = space < 0 ? "" : line.slice(space + 1);
try {
if (command === "add") this.#model.add(argument);
else if (command === "done" && /^\d+$/.test(argument)) this.#model.complete(Number(argument));
else console.log(` error: cannot read '${line}'`);
} catch (err) {
if (!(err instanceof RangeError)) throw err;
console.log(` error: ${err.message}`);
}
}
}
const model = new TodoModel();
for (const view of [renderList, renderSummary]) {
model.subscribe(() => view(model.items()).forEach((line) => console.log(line)));
}
const controller = new Controller(model);
for (const line of ["add buy milk", "add write report", "done 1", "done 7", "rename 2"]) controller.handle(line);
> add buy milk
[ ] 1 buy milk
summary: 1 open, 0 done
> add write report
[ ] 1 buy milk
[ ] 2 write report
summary: 2 open, 0 done
> done 1
[x] 1 buy milk
[ ] 2 write report
summary: 1 open, 1 done
> done 7
error: no item 7
> rename 2
error: cannot read 'rename 2'
- Verdict: idiom. The model replaces its array on each change instead of changing it in place, and
items()returns it asreadonly Item[], so the compiler rejects a view that tries to change it. - Each view is a pure function from data to lines of text. The subscription connects it to the model. This is the shape that UI libraries built on render functions use.
- The model has no type for views. It knows only the
Listenertype, a function with no arguments.
package main
import (
"errors"
"fmt"
"strconv"
"strings"
)
type Item struct {
Title string
Done bool
}
// TodoModel holds the items and calls its observers after each change.
type TodoModel struct {
items []Item
observers []func()
}
func (m *TodoModel) Subscribe(f func()) { m.observers = append(m.observers, f) }
func (m *TodoModel) Items() []Item { return append([]Item(nil), m.items...) }
func (m *TodoModel) Add(title string) error {
if title == "" {
return errors.New("a title is required")
}
m.items = append(m.items, Item{Title: title})
m.changed()
return nil
}
func (m *TodoModel) Complete(n int) error {
if n < 1 || n > len(m.items) {
return fmt.Errorf("no item %d", n)
}
m.items[n-1].Done = true
m.changed()
return nil
}
func (m *TodoModel) changed() {
for _, f := range m.observers {
f()
}
}
func listView(m *TodoModel) {
m.Subscribe(func() {
for i, item := range m.Items() {
mark := " "
if item.Done {
mark = "x"
}
fmt.Printf(" [%s] %d %s\n", mark, i+1, item.Title)
}
})
}
func summaryView(m *TodoModel) {
m.Subscribe(func() {
items := m.Items()
done := 0
for _, item := range items {
if item.Done {
done++
}
}
fmt.Printf(" summary: %d open, %d done\n", len(items)-done, done)
})
}
type Controller struct{ model *TodoModel }
func (c Controller) Handle(line string) {
fmt.Println(">", line)
command, argument, _ := strings.Cut(line, " ")
var err error
switch n, convErr := strconv.Atoi(argument); {
case command == "add":
err = c.model.Add(argument)
case command == "done" && convErr == nil:
err = c.model.Complete(n)
default:
fmt.Printf(" error: cannot read '%s'\n", line)
}
if err != nil {
fmt.Println(" error:", err)
}
}
func main() {
model := &TodoModel{}
listView(model)
summaryView(model)
controller := Controller{model}
for _, line := range []string{"add buy milk", "add write report", "done 1", "done 7", "rename 2"} {
controller.Handle(line)
}
}
> add buy milk
[ ] 1 buy milk
summary: 1 open, 0 done
> add write report
[ ] 1 buy milk
[ ] 2 write report
summary: 2 open, 0 done
> done 1
[x] 1 buy milk
[ ] 2 write report
summary: 1 open, 1 done
> done 7
error: no item 7
> rename 2
error: cannot read 'rename 2'
- Verdict: idiom. The observers are a slice of functions. Each view is a function that subscribes a closure over the model.
- The model methods return an
error, and the controller turns it into a message. The model has no idea where its errors are shown. Itemsreturns a copy of the slice, so a view cannot change the stored items through the slice it gets.- In a Go web server, an
http.Handlerplays the controller and anhtml/templateplays the view. The node page shows that form.
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Clone)]
struct Item {
title: String,
done: bool,
}
#[derive(Default)]
struct TodoModel {
items: Vec<Item>,
observers: Vec<Box<dyn Fn(&[Item])>>,
}
impl TodoModel {
fn subscribe(&mut self, f: impl Fn(&[Item]) + 'static) {
self.observers.push(Box::new(f));
}
fn add(&mut self, title: &str) -> Result<(), String> {
if title.is_empty() {
return Err("a title is required".into());
}
self.items.push(Item { title: title.into(), done: false });
self.changed();
Ok(())
}
fn complete(&mut self, n: usize) -> Result<(), String> {
let item = n.checked_sub(1).and_then(|i| self.items.get_mut(i)).ok_or(format!("no item {n}"))?;
item.done = true;
self.changed();
Ok(())
}
// The model passes a read-only view of its items to each observer.
fn changed(&self) {
for f in &self.observers {
f(&self.items);
}
}
}
fn list_view(items: &[Item]) {
for (i, item) in items.iter().enumerate() {
println!(" [{}] {} {}", if item.done { "x" } else { " " }, i + 1, item.title);
}
}
fn summary_view(items: &[Item]) {
let done = items.iter().filter(|item| item.done).count();
println!(" summary: {} open, {done} done", items.len() - done);
}
struct Controller {
model: Rc<RefCell<TodoModel>>,
}
impl Controller {
fn handle(&self, line: &str) {
println!("> {line}");
let (command, argument) = line.split_once(' ').unwrap_or((line, ""));
let mut model = self.model.borrow_mut();
let result = match (command, argument.parse::<usize>()) {
("add", _) => model.add(argument),
("done", Ok(n)) => model.complete(n),
_ => Err(format!("cannot read '{line}'")),
};
if let Err(e) = result {
println!(" error: {e}");
}
}
}
fn main() {
let model = Rc::new(RefCell::new(TodoModel::default()));
model.borrow_mut().subscribe(list_view);
model.borrow_mut().subscribe(summary_view);
let controller = Controller { model: Rc::clone(&model) };
for line in ["add buy milk", "add write report", "done 1", "done 7", "rename 2"] {
controller.handle(line);
}
}
> add buy milk
[ ] 1 buy milk
summary: 1 open, 0 done
> add write report
[ ] 1 buy milk
[ ] 2 write report
summary: 2 open, 0 done
> done 1
[x] 1 buy milk
[ ] 2 write report
summary: 1 open, 1 done
> done 7
error: no item 7
> rename 2
error: cannot read 'rename 2'
- Verdict: idiom. The model pushes a shared slice
&[Item]to each observer, instead of each view holding a reference back to the model. A view that heldRc<RefCell<TodoModel>>would try to borrow the model while the controller holds it mutably, andRefCellwould panic at run time. - The views are plain functions, so
subscribe(list_view)needs no closure. - The controller shares the model through
Rc<RefCell<...>>becausemainand the controller both refer to it.
Consequences
Benefits.
- The rules live in one place, without a screen. The model has no imports from the user interface, so a test can call
addandcompleteand check the result with no window and no server.56 - Several views of one model stay consistent. Fowler describes the classic MVC example: a spreadsheet window and graphs of the same data in separate windows. The spreadsheet window does not need to know which other windows are open. It changes the model, and the observers update.5
- A view can be added without a change to the model or the controller. In the example files, a third view is one more subscription.
- Each part changes for its own reasons. ASP.NET Core gives the reason: user interface logic tends to change more often than business logic, and code that mixes the two must change each time the user interface changes.6
Liabilities.
The flow of control is implicit. Fowler writes that the problem with Observer Synchronization "is the core problem of the observer pattern itself - you can't tell what is happening by reading the code".5 A change to the model can start a chain of updates that no single method shows. The Observer pattern node covers the failure modes: update order, updates that change the model again, and observers that are never removed.
The alternative, where the controller updates each view itself, has the opposite fault. Fowler calls it Flow Synchronization.5 The controller must know every view, and a controller that forgets one view leaves it stale:
This code runs but gives a wrong answer on purpose.
class TodoModel:
def __init__(self):
self.items = []
def add(self, title):
self.items.append(title)
class ListView:
def __init__(self, model):
self.model = model
self.text = ""
def refresh(self):
self.text = ", ".join(self.model.items)
class CountView:
def __init__(self, model):
self.model = model
self.text = ""
def refresh(self):
self.text = f"{len(self.model.items)} items"
class Controller:
def __init__(self, model, list_view, count_view):
self.model = model
self.list_view = list_view
self.count_view = count_view
def add(self, title):
self.model.add(title)
self.list_view.refresh()
# bug: self.count_view.refresh() is missing
model = TodoModel()
list_view, count_view = ListView(model), CountView(model)
list_view.refresh()
count_view.refresh()
controller = Controller(model, list_view, count_view)
controller.add("buy milk")
controller.add("write report")
print("list: ", list_view.text)
print("count:", count_view.text)
list: buy milk, write report
count: 0 items
The model holds two items, and the count view still shows the state before the first command. With observers, the count view would subscribe once, and no controller method could forget it.
Controllers grow. In web MVC, the controller is the entry point for each request, and logic that has no other home lands there. ASP.NET Core advises that controllers should not have too many responsibilities, and that business logic belongs in the domain model.6 A controller that validates, computes prices and sends mail has become the model, and the rules are again tied to the user interface.
The names do not mean one thing. Fowler calls MVC "one of the most quoted (and most misquoted) patterns around".4 In Smalltalk, the controller handles mouse and keyboard input for one view. In Rails, the controller handles an HTTP request and picks a template.7 In Django, the same role is the framework itself, and a "view" is what other frameworks call a controller.8 A discussion of MVC should say which form it means.
The view and controller split often has no value. Widget toolkits handle the raw input in the widget. Swing puts the view and the controller of a component into one UI object.9 A separate controller class for each widget adds code and no separation.
When not to use it
For a program with one output and no interaction. A script that reads a file and prints a report has no user input to interpret and one presentation. A function that computes the data and a function that formats it give the separation that matters.
When the toolkit gives a different split. A toolkit with data binding, or one that gives each widget its own input handling, expects a different structure, such as a presenter or a view model. Forcing a Smalltalk-style controller onto each widget fights the toolkit. Fowler writes that the parts of MVC that clearly worked, and stayed as Smalltalk developed, were Separated Presentation and Observer Synchronization.5 Keep those, and use the structure the toolkit expects for the rest.
As a reason to split thin code into three files. A form that reads two fields and writes one row has almost no model. Three classes for it add indirection without a rule to protect.
Variants and related patterns
Application Model. Classic MVC had no good place for view logic and view state, such as whether a button is enabled. VisualWorks Smalltalk added the Application Model, a construct that moves towards Presentation Model, to hold them.5
Model-View-Presenter. The widgets handle the user's input themselves and pass it to a presenter, which works with the model. Fowler describes two forms. In Supervising Controller, the view handles the presentation that it can describe declaratively, and the presenter handles the complex cases. In Passive View, the presenter does all the work on the widgets, and the widgets do not see the model.5
Humble View. Move as much behavior as possible out of the objects that are hard to test, so that the screen is a thin layer that a test can replace. Passive View and Presentation Model are two ways to do it.5 With Dependency injection, a test gives the presenter a fake view and checks what it receives. See Unit testing.
Web MVC, MTV. The request and response form of the solution section. A router picks a controller, the controller calls the model and picks a view, and the view renders the response.67 Django names the same parts model, template and view.8
Observer. The link between the model and its views in the classic form. See Observer pattern.
Composite. Nested views, where a window contains panes that contain views. See Composite pattern.
Strategy. A view delegates its response to input to a controller, and a different controller changes the response without a change to the view.3 See Strategy pattern.
Mediator. The controller of a form that holds the rules joining its widgets plays the role of a mediator. See Mediator pattern.
Command. A controller can turn each user action into a command object. Each command can then be queued, logged or undone. See Command pattern.
Known uses
- Smalltalk-80: the MVC framework, with views registered as dependents of a model, as Krasner and Pope describe.2
- Java Swing: JTable.java at jdk-21-ga.
setModelremoves the table from the listeners of the oldTableModeland adds it to the listeners of the model it receives. The table observes its model, and the model knows only theTableModelListenerinterface.119 - Ruby on Rails: Action Controller is "the C in the Model View Controller (MVC) pattern". After the router matches a controller to a request, the controller fetches or saves data through a model and uses a view to create the output.7
- ASP.NET Core MVC: requests are routed to a controller, which works with the model and chooses the view.6
- Django: model, template and view, with the URL configuration in the role of the controller.8
References
- Trygve Reenskaug, Models-Views-Controllers, technical note, 10 December 1979 (doi:10.5281/zenodo.3676092), sections MODELS, VIEWS, CONTROLLERS and EDITORS
- Krasner and Pope, A cookbook for using the model-view controller user interface paradigm in Smalltalk-80, JOOP 1(3), 1988, the dependency mechanism between a model and its views (changed and update messages)
- Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 1, Introduction, section Design Patterns in Smalltalk MVC
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Model View Controller, pattern summary; the book's Chapter 14
- Martin Fowler, GUI Architectures, 18 July 2006, sections Model View Controller, VisualWorks Application Model, Model-View-Presenter (MVP) and Humble View
- Microsoft Learn, Overview of ASP.NET Core MVC, MVC pattern; Model Responsibilities; Controller Responsibilities
- Ruby on Rails Guides, Action Controller Overview, 1. Introduction
- Django 5.2 documentation, FAQ, General, Django appears to be a MVC framework, but you call the Controller the "view", and the View the "template". How come you don't use the standard names?
- Amy Fowler, A Swing Architecture Overview, Oracle Java SE technical article, Swing architecture is loosely based on the traditional MVC design (separable model architecture)
- The Python Standard Library, html, Python 3.14, html.escape
- OpenJDK jdk-21-ga source, javax/swing/JTable.java, JTable.setModel, lines 3744 to 3756
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 8SSG44 Edit this page History Report an error Markdown