MVC, MVP, and MVVM
What you will learn on this page
Section titled “What you will learn on this page”- What a user interface’s code is made of: state and rules, the words and layout shown, input handling, and drawing.
- How MVC, MVP, and MVVM each divide those four, and who knows whom in each.
- How an observer keeps a screen up to date when the model changes, and what that means for object lifetimes in C++.
- How each version is tested: a presenter with a fake view, a view model with no view at all, and an MVC controller through the text it prints.
- Where each fits in desktop, embedded, and terminal programs, and when none of them is worth it.
The problem: a screen that does everything
Section titled “The problem: a screen that does everything”The registrar wants a small terminal screen for one course: it shows
who is seated and who is waiting, and accepts enroll S1 and
drop S1. The first version is one loop.
It works, and for a one-off tool it may be enough. Its problems show when the screen grows:
- It cannot be tested without a terminal. Checking what the screen
says after a drop means feeding
std::cinand readingstd::cout. - Every concern is on every line. Parsing, the rules’ answers, the words, and the drawing are interleaved, so changing the wording means reading the parsing.
- It only redraws after its own input. If another part of the program changes the course, this screen shows old data until the user types something.
- A second toolkit means a rewrite. Moving from a terminal to a window, or to a small LCD with buttons, changes every line.
Step 1: classify a screen’s code
Section titled “Step 1: classify a screen’s code”Sort what the loop does into four kinds:
| Kind | In this screen | Changes when |
|---|---|---|
| State and rules | the course, its seats, its waitlist | the registrar’s rules change |
| Presentation logic | “1 of 2 seats taken”, “S3 is waiting, position 1” | the wording or layout changes |
| Input handling | turning enroll S1 into “enroll this student” |
the controls change |
| Drawing | writing lines to the terminal | the toolkit changes |
All three patterns put state and rules in a model that knows nothing about screens, and drawing in a view. They differ in where presentation logic and input handling go, and in which objects know about which:
- MVC: the view reads the model and draws itself; a controller handles input.
- MVP: a presenter handles input and does all presentation logic; the view is passive and only draws what it is told.
- MVVM: a view model holds the screen’s state as properties and offers commands; the view binds to it, and the view model never calls the view.
The example builds all three over the same model and the same words, types the same script into each, and checks that they print the same text.
The shared parts
Section titled “The shared parts”The model is the course, plus a way to announce changes:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The model: one course and its rules. It knows nothing about screens or// input; it only announces that it changed, and lets anyone read it.// All three versions (MVC, MVP, MVVM) use this same class unchanged.// Owns its Course by value. Views, presenters, and view models hold a// plain pointer to a Roster, so a Roster must outlive all of them.class Roster {public: // Takes the course by value and moves it into the member: the caller's // course (often a temporary) is handed over, not copied a second time. explicit Roster(domain::Course course) : course_{std::move(course)} {} // Not copyable: views and presenters point at this object, and a copy // would be a second roster that none of them watch. Deleting the copy // operations also means the compiler declares no move operations, so // a Roster cannot be moved either. Roster(const Roster&) = delete; // views and presenters point at it Roster& operator=(const Roster&) = delete;
// Read-only access: a screen may look at the course but cannot change // it without going through enroll and drop below.
const domain::Course& course() const { return course_; }
// The two actions. Each passes the request to the course, returns the // course's answer unchanged, and announces a change only if the // course really changed (see roster.cpp). domain::JoinResult enroll(const domain::StudentId& student); domain::LeaveResult drop(const domain::StudentId& student);
// Called after every change. It says nothing about what changed: // each observer reads what it shows. // `listener` is any function taking nothing and returning nothing, // usually a lambda. The returned Subscription keeps it connected; when // the Subscription is destroyed, the listener is disconnected. // [[nodiscard]] makes the compiler warn if a caller drops the result, // which would disconnect the listener at once. The function is const // because subscribing does not change the course (see Signal::connect). [[nodiscard]] ui::Subscription on_change(std::function<void()> listener) const { return changed_.connect(std::move(listener)); }
private: domain::Course course_; // the state and its rules, owned by value ui::Signal changed_; // the list of listeners to call after a change};It announces a change only when the course really changed. A repeated enroll, or a drop of someone absent, says nothing, so no screen redraws:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Asks the course to enroll the student, then tells every listener if// that changed the course. Both `seated` and `waitlisted` add the student// somewhere, so both announce; only `already_in_course` changed nothing.// The listeners run inside emit(), before enroll returns, so a screen has// already redrawn by the time the caller sees the result.domain::JoinResult Roster::enroll(const domain::StudentId& student) { const domain::JoinResult result = course_.enroll(student); // take_events() hands back the events the course recorded and empties // its list. The result is thrown away on purpose: nothing here sends // them, and emptying the list stops it growing forever. course_.take_events(); // this example shows the course; it does not publish events if (result != domain::JoinResult::already_in_course) changed_.emit(); return result;}
// The same shape for drop: leaving a seat (which may promote the next// student in line) or leaving the waitlist both change the course;// `not_in_course` changes nothing, so no listener is called.domain::LeaveResult Roster::drop(const domain::StudentId& student) { const domain::LeaveResult result = course_.drop(student); course_.take_events(); // discard the recorded events, as in enroll if (result != domain::LeaveResult::not_in_course) changed_.emit(); return result;}The course still records its domain events, as on the DDD page;
Roster takes them and drops them, because this screen only needs
to know that something changed, not what. A program that also sends
notifications would publish them, as the registry on that page does.
The announcement is an observer, in a smaller form than on the Observer page:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Proof of a connection: destroying it, or calling cancel, disconnects.// It holds the signal's slots weakly, so it may outlive the signal.// What it stores: a std::weak_ptr to the signal's table of slots (the// table, detail::Slots, maps a number to each connected function) and the// number of its own entry. A weak_ptr does not keep the table alive; it// can only ask "does the table still exist?" (lock). This is RAII: the// connection lasts exactly as long as this object, with no manual// "unsubscribe" call to forget.class Subscription {public: Subscription() = default; // connected to nothing // Move-only, like std::unique_ptr: one connection has one owner. // The defaulted move constructor moves the weak_ptr, which leaves // `other` empty, so only the new object will ever disconnect. Subscription(Subscription&& other) noexcept = default; // Move assignment replaces this connection with `other`'s: first // disconnect whatever this object held, then take over `other`'s // table pointer and id. `this != &other` guards against `s = std::move(s)`, // which would otherwise cancel the very connection it means to keep. Subscription& operator=(Subscription&& other) noexcept { if (this != &other) { cancel(); slots_ = std::move(other.slots_); // other.slots_ is now empty id_ = other.id_; } return *this; } // No copies: two objects owning one connection would both erase it. Subscription(const Subscription&) = delete; Subscription& operator=(const Subscription&) = delete; ~Subscription() { cancel(); } // destroying the proof disconnects
// Disconnects now; safe to call more than once, and after the signal // is gone. lock() turns the weak_ptr into a shared_ptr if the table // still exists, or an empty one (false in the `if`) if the signal has // been destroyed. Only in the first case is there an entry to erase. // Then reset() empties the weak_ptr, so a second cancel does nothing. // noexcept: it is called from the destructor, which must not throw. void cancel() noexcept { if (const std::shared_ptr<detail::Slots> slots = slots_.lock()) slots->slots.erase(id_); slots_.reset(); }
private: // Only Signal::connect may make a live Subscription: the constructor // that takes a table and an id is private, and `friend` lets Signal // call it. friend class Signal; Subscription(std::weak_ptr<detail::Slots> slots, std::size_t id) : slots_{std::move(slots)}, id_{id} {}
std::weak_ptr<detail::Slots> slots_; // empty when connected to nothing std::size_t id_ = 0; // the key of this slot in the table};
// "Something changed": calls every connected slot, in connection order.// A slot must not connect or cancel while it is being called; the// Observer page shows a list that allows that.// A "slot" is one connected function. The signal owns the table of slots// through a std::shared_ptr; each Subscription points at the same table// through a std::weak_ptr. When the signal is destroyed, the table goes// with it, and every Subscription's lock() then finds nothing.class Signal {public: Signal() = default; Signal(const Signal&) = delete; // a copy would share the slots Signal& operator=(const Signal&) = delete;
// const: connecting does not change the thing being observed. // It still compiles, because `const` here protects the shared_ptr // member, not the table it points to. // Steps: take the next unused number (next_id++ gives the current // value, then adds one), store the function under that number, and // return a Subscription that remembers the table and the number. // Numbers only grow, and std::map keeps its keys sorted, so walking // the map visits slots in the order they were connected. [[nodiscard]] Subscription connect(std::function<void()> slot) const { const std::size_t id = slots_->next_id++; slots_->slots.emplace(id, std::move(slot)); // move the function in, no copy return Subscription{slots_, id}; // the shared_ptr converts to a weak_ptr }
// Calls every connected function, one after another, before returning. // Each entry is a (number, function) pair: entry.second is the // function, and the `()` after it calls it. void emit() const { for (const auto& entry : slots_->slots) entry.second(); }
private: // Made once, when the Signal is built. make_shared creates the table // and the shared_ptr that owns it in one step. std::shared_ptr<detail::Slots> slots_ = std::make_shared<detail::Slots>();};How this code works: Signal and Subscription: who owns the slots
The table. A Signal owns one detail::Slots object through a
std::shared_ptr: a std::map from a number to a function, and the
next number to hand out, starting at 1.
- Connecting. The MVP presenter’s
startcallsroster_->on_change(lambda), which callschanged_.connect(lambda).connecttakes number 1 (and setsnext_idto 2), stores the lambda under key 1, and returns aSubscriptionholding astd::weak_ptrto the table and the number 1. The presenter keeps thatSubscriptionin itssubscription_member. - Emitting. When
Roster::enrollchanges the course, it callschanged_.emit().emitwalks the map in key order and calls each function. Here that is the presenter’s lambda, which callsshow_roster. All of this happens beforeemit, and soenroll, returns. - Disconnecting. When the presenter is destroyed, its
subscription_is destroyed, and its destructor callscancel.lock()finds the table still alive, soerase(1)removes the lambda. A lateremitcalls nobody, so the destroyed presenter is never reached. - If the signal goes first. If the roster (and its
Signal) were destroyed while aSubscriptionstill existed, the table would be destroyed with it, because the subscriptions only holdweak_ptrs.lock()then returns an empty pointer, theifis false, andcancelerases nothing. That is what “may outlive the signal” means.
Who owns what. The signal owns the table and the functions in it.
Each subscription owns only its right to remove one entry. Nobody
owns the presenter or view through the signal: the lambda captures a
plain this, which is why the subscription must be destroyed no later
than the object this points at.
connectreturns aSubscription, and destroying it disconnects. A view that is destroyed therefore stops being called, without remembering to unsubscribe.- The subscription holds the slots weakly, through a
std::weak_ptr, so it may outlive the signal; cancelling then does nothing. connectisconst. Subscribing to a roster does not change the roster, so a view that holds aconst model::Roster&may subscribe. This compiles because the slots live behind astd::shared_ptr, whose pointee aconstsignal may still change.- It is simpler than the Observer page’s list: while a slot is being called, it must not connect, cancel, or destroy a subscription to the same signal, nor destroy the object that owns the signal. Destroying a subscription erases its slot, and erasing the slot that is running is undefined behaviour. None of the screens here do any of these.
The words on the screen are plain functions, shared so the outputs can be compared:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Plain functions: each takes what it needs to word one thing and returns// new text. None of them changes the course, prints anything, or keeps// state, which is why all three versions can share them.
// The whole screen as three lines, read fresh from the course each time:// "CS101 Software Design, 1 of 2 seats taken"// " seated: S1" (ids in seat order, or "none")// " waiting: none" (ids in waitlist order, or "none")std::vector<std::string> screen(const domain::Course& course);
// The message after an enroll, chosen from the course's answer:// "S1 has a seat", "S3 is waiting, position 1" (the place is found by// looking the student up in the course's waitlist), or// "S2 is already in CS101".std::string enrolled(const domain::StudentId& student, domain::JoinResult result, const domain::Course& course);// The message after a drop: "S1 left CS101", "S3 left the waitlist", or// "S7 is not in CS101".std::string dropped(const domain::StudentId& student, domain::LeaveResult result, const domain::Course& course);// Error messages for input that never reaches the model, such as// "'s9' is not a student id, such as S1". std::string_view is a cheap,// read-only view of text owned by someone else; the result is a new string.std::string not_a_student_id(std::string_view typed);std::string unknown_command(std::string_view typed);
// A typed line, split at the first space: "enroll S1" is {"enroll", "S1"}.// With no space at all, the whole line is the command and the argument is// empty: "list" is {"list", ""}. Only the first space splits, so// "enroll S1 S2" is {"enroll", "S1 S2"}. Both parts are copies, so they// stay valid after the typed line is gone.struct Typed { std::string command; std::string argument;};Typed split(std::string_view line);Which class calls these functions is exactly what differs between the three versions.
MVC: the view observes the model
Section titled “MVC: the view observes the model”Text description of the diagram
A component diagram with five boxes. A typed line goes to the RosterController, which handles input. The controller calls enroll and drop on the model, a Roster holding state and rules, and calls show_message on the view. The model notifies the view through on_change, shown as a dashed arrow, and the view, an mvc RosterView, reads the course from the model and draws it to the terminal. The model has no arrow to the controller and knows neither class.
Diagram source (Mermaid)
flowchart LR
In["typed line"]
C["RosterController<br/>input handling"]
M["model Roster<br/>state and rules"]
V["mvc RosterView<br/>reads the model and draws"]
Out["terminal"]
In --> C
C -->|enroll, drop| M
C -->|show_message| V
M -.->|on_change| V
V -->|reads course| M
V --> OutVerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The view reads the model and draws it whenever the model says it// changed. It is concrete: it writes to a terminal stream.// It owns nothing but its subscription: the roster and the stream belong// to whoever built the view, and the view only points at them.class RosterView {public: // Subscribes to the roster; both must outlive the view. // The roster is taken as `const`: the view may read it and subscribe // to it, but has no way to change it. RosterView(const model::Roster& roster, std::ostream& out); // Deleting the copy operations also stops the compiler from making // move operations, so a RosterView can be neither copied nor moved. RosterView(const RosterView&) = delete; // the subscription points at this object RosterView& operator=(const RosterView&) = delete;
void render() const; // the whole screen, read from the model // Prints one message line, starting with "-- ", such as // "-- S1 has a seat". The controller calls it; the model never does. void show_message(const std::string& text) const;
private: // Non-owning pointers to the caller's objects: the view never deletes // them. The constructor sets them from references, so they are never null. const model::Roster* roster_; std::ostream* out_; // Members are destroyed in reverse order of declaration, so this one, // declared last, is destroyed first and disconnects the lambda that // calls render() before anything else in the view is gone. ui::Subscription subscription_; // last: cancelled before the rest is destroyed};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Stores where the roster and the stream are, then subscribes. The// lambda `[this] { render(); }` captures only the pointer `this`, so each// time the roster announces a change, it calls render() on this very// view. The members are set in declaration order, so roster_ and out_// are ready before subscription_ connects the lambda. Nothing is drawn// yet: the first paint is an explicit render() call (see main.cpp).RosterView::RosterView(const model::Roster& roster, std::ostream& out) : roster_{&roster}, out_{&out}, subscription_{roster.on_change([this] { render(); })} {}
// Draws the whole screen from the current course, every time. It never// works out "what changed": it asks text::screen for all three lines and// writes each one. *out_ is the stream the pointer refers to.void RosterView::render() const { for (const std::string& line : text::screen(roster_->course())) *out_ << line << '\n';}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The controller turns input into calls on the model. It does not draw// the roster; it only tells the view what the screen alone cannot show.// It holds non-owning pointers to both; the roster and the view must// outlive it. It subscribes to nothing, so, unlike the view, it could be// copied safely.class RosterController {public: // The roster is non-const here: the controller is the one that changes // it. `&roster` stores the address of the caller's object. RosterController(model::Roster& roster, const RosterView& view) : roster_{&roster}, view_{&view} {}
// Handles one typed line, such as "enroll S1" or "drop S7". void handle(std::string_view line);
private: model::Roster* roster_; const RosterView* view_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One typed line, in three steps: split it, refuse what is not a known// command or a valid id (a message only; the model is not touched), then// call the model and add the message that describes its answer.void RosterController::handle(std::string_view line) { const text::Typed typed = text::split(line); // "drop S1" is {"drop", "S1"} // Early return: anything but the two commands gets a message and stops. if (typed.command != "enroll" && typed.command != "drop") { view_->show_message(text::unknown_command(typed.command)); return; } // parse returns a std::optional<StudentId>: an id if the text is one // (such as "S1"), or empty if not (such as "s9"). `auto` saves writing // that type out. An empty optional is false, so `!student` means // "not a valid id". const auto student = domain::StudentId::parse(typed.argument); if (!student) { view_->show_message(text::not_a_student_id(typed.argument)); return; } // The model's change redraws the view through its subscription; // the controller adds the message. // So the order on screen is: the new roster first, if the model changed // (printed inside roster_->enroll or drop, by the view's lambda), then the message. // `*student` takes the StudentId out of the optional; it is safe because // the check above returned early when the optional was empty. if (typed.command == "enroll") { const domain::JoinResult result = roster_->enroll(*student); view_->show_message(text::enrolled(*student, result, roster_->course())); } else { const domain::LeaveResult result = roster_->drop(*student); view_->show_message(text::dropped(*student, result, roster_->course())); }}How this code works: One request through MVC: enroll S3
At this point in the script, S1 and S2 hold both seats of CS101 and
nobody is waiting. type_script prints > enroll S3, then calls the
lambda from run_mvc, which calls controller.handle("enroll S3").
- Controller, input handling.
text::splitgives{"enroll", "S3"}. The command is known, anddomain::StudentId::parse("S3")returns an id, so neither early return is taken. - Controller to model.
roster_->enroll(S3)callsCourse::enroll. Both seats are taken, so S3 joins the waitlist and the answer iswaitlisted.Rosterdiscards the recorded events and, because the answer is notalready_in_course, callschanged_.emit(). - Model to view, through the observer.
emitcalls the lambda the view registered in its constructor, which callsrender.renderreads the course and prints the three linesCS101 Software Design, 2 of 2 seats taken,seated: S1 S2, andwaiting: S3. Only now doesemitreturn, thenRoster::enroll, handingwaitlistedback to the controller. - Controller to view, the message.
text::enrolledfinds S3 at position 1 of the waitlist, andshow_messageprints-- S3 is waiting, position 1.
Who owns what. run_mvc owns the roster, the stream, the view,
and the controller, as local variables. The view and the controller
hold only pointers. Where the boundary is. The model never names
a view or a controller: in step 3 it calls a std::function it was
given, without knowing whose it is. The controller calls both the
model and the view; the view only reads the model.
How the work is divided:
- The view knows the model and decides how to show it: it calls
text::screenitself. When the model changes, the view’s subscription callsrender. - The controller knows the model and the view. It parses the typed line and checks the id, calls the model, and adds the message that the screen alone does not show, such as “S2 is already in CS101”.
- The model knows neither. A second view, such as a count on another screen, can subscribe without the model changing.
On lifetimes: the view’s subscription holds a lambda that captures
this. A copy would not compile anyway, because Subscription is
move-only. The danger is a move: the compiler would generate a
move constructor, and the moved-to view would own a subscription
whose lambda still calls the old object. Declaring the copy
operations = delete also stops the compiler from declaring the
move operations, so the view can be neither copied nor moved. The
subscription is the last member, so it is destroyed first and
the model cannot call a half-destroyed view.
MVP: the presenter decides, the view obeys
Section titled “MVP: the presenter decides, the view obeys”Text description of the diagram
A component diagram with six boxes. A typed line goes to the TerminalRosterView, which draws and forwards input. It calls enroll_requested, drop_requested, and unknown_command on the RosterPresenter, which holds the presentation logic. The presenter calls show_screen and show_message on the mvp RosterView interface, which the TerminalRosterView implements, shown as a dashed arrow. The presenter calls enroll and drop on the model Roster and reads its course, and the model notifies the presenter through on_change, also dashed. The terminal view draws to the terminal. The view has no arrow to the model.
Diagram source (Mermaid)
flowchart LR
In["typed line"]
TV["TerminalRosterView<br/>draws, forwards input"]
VI["mvp RosterView<br/>interface"]
P["RosterPresenter<br/>presentation logic"]
M["model Roster<br/>state and rules"]
Out["terminal"]
In --> TV
TV -->|enroll_requested, drop_requested, unknown_command| P
P -->|show_screen, show_message| VI
TV -.->|implements| VI
P -->|enroll, drop, reads course| M
M -.->|on_change| P
TV --> OutVerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Everything the presenter may ask of a screen. A passive view shows// exactly what it is given and reports what the user did; it never// reads the model.// An interface: `virtual ... = 0` means "no code here; every concrete// view must supply its own". The terminal view and the tests' FakeView// both do, and the presenter calls whichever one it was given.class RosterView {public: // A virtual destructor, so destroying a view through a RosterView // pointer runs the concrete view's destructor too. virtual ~RosterView() = default; // Show exactly these lines as the whole screen. Takes a const // reference: the view reads the caller's lines, without a copy, and cannot change them. virtual void show_screen(const std::vector<std::string>& lines) = 0; // Show one message, already worded by the presenter. virtual void show_message(const std::string& text) = 0;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The presenter decides everything the user sees: it handles the view's// events, calls the model, and formats what the view shows. It knows the// view only through the interface, so a test can pass a fake.class RosterPresenter {public: // Both must outlive the presenter. // The constructor only stores the two addresses; it subscribes and // draws nothing until start() is called. RosterPresenter(model::Roster& roster, RosterView& view) : roster_{&roster}, view_{&view} {} // Neither copyable nor movable, for the same reason as the MVC view: // start() gives the roster a lambda that captures `this`. RosterPresenter(const RosterPresenter&) = delete; // the subscription points at this object RosterPresenter& operator=(const RosterPresenter&) = delete;
void start(); // shows the roster, and keeps it shown as it changes
// The user's gestures, as the view reports them. // `typed` is the text after the command word, such as "S1"; the // presenter, not the view, decides whether it is a valid id. void enroll_requested(std::string_view typed); void drop_requested(std::string_view typed); // `typed` here is the command word that was not recognised. void unknown_command(std::string_view typed);
private: void show_roster(); // words the whole screen and hands it to the view
model::Roster* roster_; // not owned RosterView* view_; // not owned; any class that implements RosterView ui::Subscription subscription_; // empty until start(); declared last};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Subscribe first, then paint once. From now on, every change to the// roster, from this presenter or from anywhere else, calls show_roster.// `subscription_ = ...` uses Subscription's move assignment: the empty// subscription is replaced by the new connection.void RosterPresenter::start() { subscription_ = roster_->on_change([this] { show_roster(); }); show_roster(); // the first paint; no change has happened yet}
// The user asked to enroll whatever they typed. Check the text first: a// bad id gets a message and the model is never called, so nothing redraws.// Otherwise call the model, which redraws the screen through start()'s// subscription before it returns, and then word its answer as a message.void RosterPresenter::enroll_requested(std::string_view typed) { const auto student = domain::StudentId::parse(typed); // optional: empty if not an id if (!student) { view_->show_message(text::not_a_student_id(typed)); return; } const domain::JoinResult result = roster_->enroll(*student); // redraws, if it changed // The message is worded from the course as it is now, after the // change, so "waiting, position 1" counts this student. view_->show_message(text::enrolled(*student, result, roster_->course()));}
// The only place that words the whole screen. The presenter reads the// model and gives the view finished lines; the view never sees a Course.void RosterPresenter::show_roster() { view_->show_screen(text::screen(roster_->course())); }// The same steps as enroll_requested, for a drop. A drop that frees a// seat may promote the next student; the redraw shows that, because the// screen is read again from the course.void RosterPresenter::drop_requested(std::string_view typed) { const auto student = domain::StudentId::parse(typed); if (!student) { view_->show_message(text::not_a_student_id(typed)); return; } const domain::LeaveResult result = roster_->drop(*student); view_->show_message(text::dropped(*student, result, roster_->course()));}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The real screen: prints what it is told, and turns each typed line// into one of the presenter's gestures.// `final`: no class may derive from this one. `override` on the two// functions asks the compiler to check that they really replace the// interface's functions (a typo in a name or parameter becomes an error).class TerminalRosterView final : public RosterView {public: explicit TerminalRosterView(std::ostream& out) : out_{&out} {}
// The second half of a two-way link. The presenter needs the view in // its constructor, so the view is built first, without a presenter, // and is told about it here, once both exist. void attach(RosterPresenter& presenter) { presenter_ = &presenter; } // must outlive the view's use // Splits one typed line and calls the matching gesture on the // presenter: "enroll S1" becomes enroll_requested("S1"). Throws // std::logic_error if attach has not been called yet. void typed(std::string_view line);
// Both print to the stream and decide nothing: lines as given, and a // message as "-- " followed by the text. void show_screen(const std::vector<std::string>& lines) override; void show_message(const std::string& text) override;
private: std::ostream* out_; RosterPresenter* presenter_ = nullptr; // set by attach, not owned};How this code works: One request through MVP: drop S1
At this point S1 and S2 are seated and S3 is waiting. run_mvp’s
lambda calls view.typed("drop S1") on the TerminalRosterView.
- View, input only.
typedchecks that a presenter is attached, splits the line into{"drop", "S1"}, and callspresenter_->drop_requested("S1"). The view decides only which gesture this was; it does not check the id. - Presenter, presentation logic.
drop_requestedparses"S1"into an id, then callsroster_->drop(S1). - Model.
Course::dropfinds S1 in a seat, removes them, and promotes S3, the first student waiting, into the free seat. The answer isleft_seat, soRostercallschanged_.emit(). - Model to presenter, through the observer. The lambda from
startcallsshow_roster, which builds the lines withtext::screenand callsview_->show_screen(lines).view_is aRosterView*, so this is a virtual call; it lands inTerminalRosterView::show_screen, which printsCS101 Software Design, 2 of 2 seats taken,seated: S2 S3, andwaiting: none. - Presenter to view, the message. Back in
drop_requested,text::droppedgivesS1 left CS101, andview_->show_messageprints-- S1 left CS101.
Where the boundary is. The view calls three presenter functions
and implements two interface functions; it never sees a Course.
The presenter sees the view only as a RosterView, which is why the
tests can pass a FakeView instead. Who owns what. run_mvp owns
the view and the presenter; they point at each other, and both point
at the roster, which run_mvp declared first.
How the work is divided:
- The view is passive. It has two output functions and no decisions beyond “which control was used”, and it never reads the model. (Here the interface shares a header with the presenter, for brevity; in a larger program it would have its own header, so a view could be compiled without the domain.)
- The presenter does all presentation logic: it checks the typed id, calls the model, chooses the words, and observes the model so that a change made elsewhere is shown too.
- The presenter knows the view only through
RosterView, an interface, so a test can pass a fake that records what it was told. - The link is two-way. The presenter needs the view to show
things, and the view needs the presenter to report input. The
example builds the view first, then the presenter, and then calls
attach. A larger program often gives the view an interface for the presenter’s side too, so the view does not depend on the concrete presenter.
This form is often called passive view. A variant called supervising controller lets the view bind simple fields to the model directly, and keeps only harder logic in the presenter: less code, but less of the screen is covered by presenter tests.
MVVM: the view binds to a view model
Section titled “MVVM: the view binds to a view model”Text description of the diagram
A component diagram with five boxes. A typed line goes to the mvvm TerminalRosterView, which binds and draws. It sets the student_text property of the RosterViewModel and calls its enroll, drop, and unknown_command commands. The view model holds properties and commands. When its screen and message properties change, the view is notified, shown as a dashed arrow. The view model calls enroll and drop on the model Roster and reads its course, and the model notifies the view model through on_change, also dashed. The view draws to the terminal. The view model has no arrow that calls the view.
Diagram source (Mermaid)
flowchart LR
In["typed line"]
TV["mvvm TerminalRosterView<br/>binds and draws"]
VM["RosterViewModel<br/>properties and commands"]
M["model Roster<br/>state and rules"]
Out["terminal"]
In --> TV
TV -->|sets student_text, calls enroll, drop, unknown_command| VM
VM -.->|screen and message changed| TV
VM -->|enroll, drop, reads course| M
M -.->|on_change| VM
TV --> OutA property is a value that announces its changes:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A value that announces its changes: the "property" a view binds to.// It is a template: T is the type of the value, so Observable<std::string>// holds a string and Observable<std::vector<std::string>> holds lines of// text. T must support `==`, which set uses to spot a real change.// Owns its value and its Signal; listeners are told after each change and// read the new value with get().template <typename T>class Observable {public: // Starts with the given value, or with T's empty value (`T{}`, such as // an empty string) if none is given. explicit Observable(T value = T{}) : value_{std::move(value)} {}
const T& get() const { return value_; }
// Notifies only when the value really changes, so a view redraws // only what is new. // Order matters: the value is stored first and the listeners are called // after, so a listener that calls get() sees the new value. void set(T value) { if (value == value_) return; // same value: nobody is told anything value_ = std::move(value); // take over the argument, no second copy changed_.emit(); }
// Connects a listener, as Roster::on_change does. Keep the returned // Subscription for as long as the listener should be called. [[nodiscard]] Subscription subscribe(std::function<void()> listener) const { return changed_.connect(std::move(listener)); }
private: T value_; Signal changed_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The view model is the screen's state and actions, as plain values and// functions. It does not know any view exists: a view binds to its// properties and calls its commands.// It owns its three properties by value and points at the roster, which it// does not own. It holds no pointer to any view.class RosterViewModel {public: // Fills the screen property from the course straight away and // subscribes to the roster, so the property follows every change. explicit RosterViewModel(model::Roster& roster); // the roster must outlive this // Not copyable or movable: its subscription's lambda captures `this`. RosterViewModel(const RosterViewModel&) = delete; // the subscription points at this object RosterViewModel& operator=(const RosterViewModel&) = delete;
// Properties. The screen and the message are for the view to show; // the student text is written by the view: what the user typed. // The first two are returned as `const` references: a view may read // them and subscribe to them, but cannot set them. student_text is // returned non-const, because writing it is the view's job. const ui::Observable<std::vector<std::string>>& screen() const { return screen_; } const ui::Observable<std::string>& message() const { return message_; } ui::Observable<std::string>& student_text() { return student_text_; }
// Commands, which read the student text. // enroll and drop take no arguments: their input is whatever student_text // holds, and the output is new values in screen and message. void enroll(); void drop(); void unknown_command(std::string_view typed);
private: model::Roster* roster_; ui::Observable<std::vector<std::string>> screen_; // the three lines to show ui::Observable<std::string> message_; // "" means "no message" ui::Observable<std::string> student_text_; // what the user typed ui::Subscription subscription_; // last: cancelled first};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The screen property starts as the course's current screen. Then the// view model subscribes: on each change, it words the screen again and// set()s the property, which notifies whoever is bound to it. The model// only reaches the view through this chain: roster, then view model, then// the screen property's listeners. message_ and student_text_ are not in// the list, so they start as empty strings.RosterViewModel::RosterViewModel(model::Roster& roster) : roster_{&roster}, screen_{text::screen(roster.course())}, subscription_{roster.on_change([this] { screen_.set(text::screen(roster_->course())); })} {}
// The enroll command. The input is the student_text property, and the// results are new values in the screen and message properties. It never// prints; a bound view does that when the properties change.void RosterViewModel::enroll() { // Clear first. set() only notifies when the value changes, so without // this, a second identical message would be ignored. Setting "" is // itself a change when a message was showing, so listeners are called // with an empty message; the terminal view prints nothing for it. message_.set(""); // so that the same message twice is still shown twice const auto student = domain::StudentId::parse(student_text_.get()); if (!student) { message_.set(text::not_a_student_id(student_text_.get())); return; } const domain::JoinResult result = roster_->enroll(*student); // updates screen_, if it changed message_.set(text::enrolled(*student, result, roster_->course()));}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The view: binds to the view model's properties and prints them when// they change, and turns each typed line into a property write and a// command. The view model never calls it.// "Binds" means: subscribes to a property and redraws when it changes.// The view model and the stream must outlive the view.class TerminalRosterView {public: TerminalRosterView(RosterViewModel& view_model, std::ostream& out); // shows the screen now // Not copyable or movable: both bindings hold lambdas capturing `this`. TerminalRosterView(const TerminalRosterView&) = delete; TerminalRosterView& operator=(const TerminalRosterView&) = delete;
// One typed line: write the argument into student_text, then run the // matching command, such as enroll for "enroll S1". void typed(std::string_view line);
private: void print_screen() const; // prints the screen property's current lines
RosterViewModel* view_model_; // not owned std::ostream* out_; // not owned // One subscription per bound property, declared last so they are // destroyed (and disconnected) before the pointers above. ui::Subscription screen_binding_; ui::Subscription message_binding_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Two bindings, made in the member list, then the first paint.// - screen: whenever the screen property changes, print all its lines.// - message: whenever the message property changes, read the new text// and print it with "-- " in front, unless it is empty (the view// model's "clear" step, which should show nothing).// Each lambda captures only `this` and reads the property again when it// runs, so it always prints the current value.TerminalRosterView::TerminalRosterView(RosterViewModel& view_model, std::ostream& out) : view_model_{&view_model}, out_{&out}, screen_binding_{view_model.screen().subscribe([this] { print_screen(); })}, message_binding_{view_model.message().subscribe([this] { const std::string& text = view_model_->message().get(); if (!text.empty()) *out_ << "-- " << text << '\n'; })} { print_screen(); // the first paint; the bindings only react to changes}
// Turns one line into "write the property, then run the command". The// view does not check the id; the view model's command does.void TerminalRosterView::typed(std::string_view line) { const text::Typed typed = text::split(line); if (typed.command == "enroll" || typed.command == "drop") { // set() copies the argument into the property; nobody is bound to // student_text here, so this notifies no one. view_model_->student_text().set(typed.argument); if (typed.command == "enroll") { view_model_->enroll(); } else { view_model_->drop(); } } else { view_model_->unknown_command(typed.command); }}How this code works: One request through MVVM: enroll S2 again
S2 already has a seat, and the message property still holds
S3 is waiting, position 1 from the previous line. run_mvvm’s lambda
calls view.typed("enroll S2").
- View writes a property.
typedsplits the line and callsstudent_text().set("S2"). The value changes (it was"S3"), but nothing is bound tostudent_text, so nothing is printed. - View runs a command.
typedcallsview_model_->enroll(). From here on, the view model never calls the view; it only sets properties, and the view’s bindings react. - Clear the message.
message_.set("")is a change, so the message binding runs, reads an empty text, and prints nothing. - Call the model.
parse("S2")succeeds, androster_->enroll(S2)answersalready_in_course.Rosterdoes not emit, so the view model’s subscription does not run, the screen property is untouched, and the screen is not redrawn. - Set the message.
message_.set("S2 is already in CS101")is a change, so the binding prints-- S2 is already in CS101.
| Step | student_text |
message |
Printed |
|---|---|---|---|
| 0 | S3 |
S3 is waiting, position 1 |
|
| 1 | S2 |
unchanged | nothing |
| 3 | S2 |
empty | nothing |
| 4 | S2 |
empty | nothing (no change to course) |
| 5 | S2 |
S2 is already in CS101 |
-- S2 is already in CS101 |
Who owns what. The view model owns its three properties; the view
owns its two bindings; run_mvvm owns the roster, the view model,
and the view, declared in that order so they are destroyed in the
reverse order. Where the boundary is. The chain of calls on a
change runs model, then view model, then the property’s listeners:
neither the model nor the view model holds a pointer to a view.
How the work is divided:
- The view model is the screen’s state, as values: the lines to
show, the message, and the text the user typed. Its commands, such
as
enroll, read that text and update the properties. - The view model holds no reference to a view. It does not know whether zero, one, or three views are bound to it. The view subscribes to the properties, so the only calls into the view are its own bindings, made when a property changes.
- The view does the binding by hand here: two subscriptions, and a property write before each command. Toolkits with data binding, such as Qt’s QML or WPF, do this wiring from a declaration; in plain C++ it is written out, which is the pattern’s main cost here.
- “Only when it changes” has a side effect. Showing the same error twice would not notify, because the message is unchanged. The commands first clear the message, and the view ignores an empty one. Rules like this are typical of binding, and need tests.
Running it
Section titled “Running it”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What the user types, the same for all three versions.// An array of pointers to fixed text (string literals), sized by the// compiler from the list: eight lines. It tries a seat, a second seat, a// waitlist place, a repeat, a bad id (lower-case s), a drop that promotes,// a drop of someone absent, and an unknown command.constexpr const char* script[] = { "enroll S1", "enroll S2", "enroll S3", "enroll S2", "enroll s9", "drop S1", "drop S7", "list",};
// A fresh two-seat course for each run. parse returns an optional; `*`// takes the code out without a check, which is safe only because "CS101"// is known to be a valid code.domain::Course software_design() { return domain::Course{*domain::CourseCode::parse("CS101"), "Software Design", 2};}
// Echoes each line, as a terminal would, and hands it to the screen.// A template, so `typed` can be any callable taking a line: each run_// function below passes a lambda that forwards to its own version's// input handler. The loop converts each `const char*` to a// std::string_view, a view of the same text with no copy.template <typename Typed>void type_script(std::ostream& out, Typed typed) { for (const std::string_view line : script) { out << "> " << line << '\n'; typed(line); }}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each function builds one version over its own roster, types the script,// and returns everything printed. All output goes to a std::ostringstream// (a stream that collects text in memory) so the three can be compared.// The declaration order is the ownership story: the roster and the stream// first, the objects that point at them after. Locals are destroyed in// reverse order, so the screen objects go (and disconnect) before the// roster they watch. The lambdas capture by reference ([&]), which is// safe because type_script finishes before any local is destroyed.std::string run_mvc() { model::Roster roster{software_design()}; std::ostringstream out; mvc::RosterView view{roster, out}; mvc::RosterController controller{roster, view}; view.render(); // the first paint: the view only redraws on a change type_script(out, [&](std::string_view line) { controller.handle(line); }); return out.str();}
std::string run_mvp() { model::Roster roster{software_design()}; std::ostringstream out; mvp::TerminalRosterView view{out}; mvp::RosterPresenter presenter{roster, view}; // needs the view, so built after it view.attach(presenter); // now the view can report input to the presenter presenter.start(); // subscribe, then the first paint type_script(out, [&](std::string_view line) { view.typed(line); }); return out.str();}
std::string run_mvvm() { model::Roster roster{software_design()}; std::ostringstream out; mvvm::RosterViewModel view_model{roster}; mvvm::TerminalRosterView view{view_model, out}; // binds and paints at once type_script(out, [&](std::string_view line) { view.typed(line); }); return out.str();}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Prints the MVP run, then checks that the other two printed exactly the// same text, character for character. `?:` picks "yes" or "no".int main() { const std::string mvp = run_mvp(); std::cout << mvp; std::cout << "MVC prints the same: " << (run_mvc() == mvp ? "yes" : "no") << '\n'; std::cout << "MVVM prints the same: " << (run_mvvm() == mvp ? "yes" : "no") << '\n';}CS101 Software Design, 0 of 2 seats taken seated: none waiting: none> enroll S1CS101 Software Design, 1 of 2 seats taken seated: S1 waiting: none-- S1 has a seat> enroll S2CS101 Software Design, 2 of 2 seats taken seated: S1 S2 waiting: none-- S2 has a seat> enroll S3CS101 Software Design, 2 of 2 seats taken seated: S1 S2 waiting: S3-- S3 is waiting, position 1> enroll S2-- S2 is already in CS101> enroll s9-- 's9' is not a student id, such as S1> drop S1CS101 Software Design, 2 of 2 seats taken seated: S2 S3 waiting: none-- S1 left CS101> drop S7-- S7 is not in CS101> list-- unknown command 'list'; try enroll S1 or drop S1MVC prints the same: yesMVVM prints the same: yesReading the output:
- The first three lines are the first paint, before any input:
renderin MVC,startin MVP, and the binding’s constructor in MVVM. - A change to the course redraws the screen first, then shows the
message: the model’s change reaches the view through the observer
while
enrollis still running, and the message is added after it returns. enroll S2a second time,enroll s9,drop S7, andlistchange nothing, so only a message appears. The model did not announce a change, so nothing redrew.- Dropping S1 promotes S3 from the waitlist, and the redrawn screen shows it, although no code in any of the three versions mentions promotion: the screen simply reads the course again.
- The last two lines compare the whole MVC and MVVM output with MVP’s.
In each run_ function, the model is declared first and the screen’s
objects after it, so they are destroyed before the model. Every
object holds the ones it uses by non-owning pointer, and each class
that subscribes cannot be copied or moved, for the reason given under
MVC.
class model::Roster
the model, shared
Data members
domain::Course course_;ui::Signal changed_;
Member functions
const domain::Course& course() const;domain::JoinResult enroll(const domain::StudentId& student);announces a changedomain::LeaveResult drop(const domain::StudentId& student);ui::Subscription on_change(std::function<void()> listener) const;
class mvc::RosterView
reads the model, draws itself
Data members
const model::Roster* roster_;non-owningui::Subscription subscription_;calls render
Member functions
void render() const;void show_message(const std::string& text) const;
class mvc::RosterController
input to model calls
Data members
model::Roster* roster_;non-owningconst RosterView* view_;non-owning
Member functions
void handle(std::string_view line);
interface (abstract class) mvp::RosterView
passive
Member functions
virtual void show_screen(const std::vector<std::string>& lines) = 0;virtual void show_message(const std::string& text) = 0;
class mvp::RosterPresenter
all presentation logic
Data members
model::Roster* roster_;non-owningRosterView* view_;non-owning, any implementationui::Subscription subscription_;
Member functions
void start();void enroll_requested(std::string_view typed);and drop_requestedvoid unknown_command(std::string_view typed);
class mvp::TerminalRosterView
final, implements mvp::RosterView
Data members
RosterPresenter* presenter_;non-owning, set by attach
Member functions
void attach(RosterPresenter& presenter);void typed(std::string_view line);
class mvvm::RosterViewModel
properties and commands, no view
Data members
model::Roster* roster_;non-owningui::Observable<std::vector<std::string>> screen_;ui::Observable<std::string> message_;ui::Observable<std::string> student_text_;ui::Subscription subscription_;last
Member functions
const ui::Observable<std::vector<std::string>>& screen() const;const ui::Observable<std::string>& message() const;ui::Observable<std::string>& student_text();written by the viewvoid enroll();and dropvoid unknown_command(std::string_view typed);
class mvvm::TerminalRosterView
binds and draws
Data members
RosterViewModel* view_model_;non-owningui::Subscription screen_binding_;and message_binding_
Member functions
void typed(std::string_view line);
Testing each version
Section titled “Testing each version”The presenter, with a fake view that records what it was told. No terminal is involved, and the checks are on the exact lines and messages:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Records what the presenter asked for, instead of drawing it.// It implements the same interface as the terminal view, so the presenter// cannot tell the difference. Each call is kept in order: screens[0] is// the first screen shown, screens[0][0] its first line. The members are// public so a test can read them directly.class FakeView final : public mvp::RosterView {public: std::vector<std::vector<std::string>> screens; // every screen, in order std::vector<std::string> messages; // every message, in order
void show_screen(const std::vector<std::string>& lines) override { screens.push_back(lines); } void show_message(const std::string& text) override { messages.push_back(text); }};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false. LLD_CHECK_EQ(actual, expected) records a// failure unless the two are equal, and prints both values when they are// not. They come from the site's small test header, lld_test.hpp. The// helpers course(capacity) and student(text) build a CS101 course and a// valid id. Every test builds its own roster, fake view, and presenter.
// start paints exactly once and says nothing: one screen, the right first// line, and no message. std::size_t{1} gives the 1 the same type as// size(), so LLD_CHECK_EQ compares like with like.LLD_TEST(start_shows_the_roster_once) { model::Roster roster{course(2)}; FakeView view; mvp::RosterPresenter presenter{roster, view}; presenter.start(); LLD_CHECK_EQ(view.screens.size(), std::size_t{1}); LLD_CHECK_EQ(view.screens[0][0], std::string{"CS101 Software Design, 0 of 2 seats taken"}); LLD_CHECK(view.messages.empty());}
// A successful enroll causes one redraw (through the subscription) and one// message: two screens in total, the second showing S1 seated// (screens[1][1] is its second line), and exactly the one message.LLD_TEST(a_seat_redraws_the_screen_then_says_so) { model::Roster roster{course(2)}; FakeView view; mvp::RosterPresenter presenter{roster, view}; presenter.start(); presenter.enroll_requested("S1"); LLD_CHECK_EQ(view.screens.size(), std::size_t{2}); LLD_CHECK_EQ(view.screens[1][1], std::string{" seated: S1"}); LLD_CHECK(view.messages == std::vector<std::string>{"S1 has a seat"});}
// "s9" is not an id (ids start with a capital S), so the model is never// called: still only the first screen, nobody seated, and the reason as// the only message.LLD_TEST(a_bad_id_changes_nothing_and_says_why) { model::Roster roster{course(2)}; FakeView view; mvp::RosterPresenter presenter{roster, view}; presenter.start(); presenter.enroll_requested("s9"); LLD_CHECK_EQ(view.screens.size(), std::size_t{1}); LLD_CHECK(roster.course().seated().empty()); LLD_CHECK(view.messages == std::vector<std::string>{"'s9' is not a student id, such as S1"});}
// The roster is changed directly, not through the presenter. The// presenter still redraws, because it observes the model, and shows no// message, because it did not make the request.LLD_TEST(a_change_made_elsewhere_still_redraws) { model::Roster roster{course(2)}; FakeView view; mvp::RosterPresenter presenter{roster, view}; presenter.start(); roster.enroll(student("S4")); // another screen, or a test, changes the model LLD_CHECK_EQ(view.screens.size(), std::size_t{2}); LLD_CHECK(view.messages.empty());}The view model, with no view at all. A test sets a property, runs a command, and reads the properties back, as a view would:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST, LLD_CHECK, and LLD_CHECK_EQ are the site's test macros from// lld_test.hpp (see the presenter tests). course(capacity) builds CS101.
// No view exists here. The test does what a view would (write// student_text, run a command) and reads the properties back. In a// one-seat course, S1 gets the seat and S2 must wait: screen line 1 is// the seated line, line 2 the waiting line.LLD_TEST(the_view_model_is_tested_through_its_properties_with_no_view) { model::Roster roster{course(1)}; mvvm::RosterViewModel view_model{roster}; view_model.student_text().set("S1"); view_model.enroll(); LLD_CHECK_EQ(view_model.screen().get()[1], std::string{" seated: S1"}); LLD_CHECK_EQ(view_model.message().get(), std::string{"S1 has a seat"});
view_model.student_text().set("S2"); view_model.enroll(); LLD_CHECK_EQ(view_model.screen().get()[2], std::string{" waiting: S2"}); LLD_CHECK_EQ(view_model.message().get(), std::string{"S2 is waiting, position 1"});}
// Counts how often the screen property notifies. The first enroll seats// S1, so the screen changes once. The second is refused as// already_in_course, so the roster announces nothing and the count stays 1.LLD_TEST(a_property_notifies_only_when_it_changes) { model::Roster roster{course(1)}; mvvm::RosterViewModel view_model{roster}; // The lambda captures `screens` by reference ([&]) and adds one each // time it runs. Keeping `binding` alive keeps it connected until the // end of the test. int screens = 0; const ui::Subscription binding = view_model.screen().subscribe([&] { ++screens; }); view_model.student_text().set("S1"); view_model.enroll(); view_model.enroll(); // already in the course: the model does not change LLD_CHECK_EQ(screens, 1);}
// "x" is not an id, so both enrolls set the same error message. Because// enroll clears the message first, the second identical message is still// a change and is announced. The listener skips the empty "clear" value,// as the terminal view does, so it records the error exactly twice.LLD_TEST(the_same_message_twice_is_announced_twice) { model::Roster roster{course(1)}; mvvm::RosterViewModel view_model{roster}; std::vector<std::string> shown; const ui::Subscription binding = view_model.message().subscribe([&] { if (!view_model.message().get().empty()) shown.push_back(view_model.message().get()); }); view_model.student_text().set("x"); view_model.enroll(); view_model.enroll(); LLD_CHECK_EQ(shown.size(), std::size_t{2});}The MVC controller, through the real view. The view is a concrete class that writes to a stream, so the test reads the text it printed. That works here because the screen is a few lines of text; with a window toolkit, it would mean inspecting widgets, which is why MVP and MVVM are often chosen for testability:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The controller is tested through the real view, by reading the text it// printed: the view is a concrete class, not an interface.// LLD_TEST, LLD_CHECK, and LLD_CHECK_EQ are the site's test macros from// lld_test.hpp. The view writes into a std::ostringstream, and out.str()// returns everything written so far as one string.
// After "enroll S1", the model holds S1, and the text is exactly the// redrawn screen followed by the message. No first paint appears, because// this test never calls view.render(). The four string pieces are joined// into one string by the compiler (adjacent literals are concatenated).LLD_TEST(the_controller_changes_the_model_and_the_view_redraws_itself) { model::Roster roster{course(2)}; std::ostringstream out; mvc::RosterView view{roster, out}; mvc::RosterController controller{roster, view}; controller.handle("enroll S1"); LLD_CHECK(roster.course().contains(*domain::StudentId::parse("S1"))); LLD_CHECK_EQ(out.str(), std::string{"CS101 Software Design, 1 of 2 seats taken\n" " seated: S1\n" " waiting: none\n" "-- S1 has a seat\n"});}
// "list" is not a command, so the model is not called and does not// announce a change: the only text is the message, with no screen.LLD_TEST(an_unknown_command_reaches_only_the_view) { model::Roster roster{course(2)}; std::ostringstream out; mvc::RosterView view{roster, out}; mvc::RosterController controller{roster, view}; controller.handle("list"); LLD_CHECK_EQ(out.str(), std::string{"-- unknown command 'list'; try enroll S1 or drop S1\n"});}What none of these tests cover is the drawing itself, such as whether a real window lays out the lines readably. The patterns make that part as thin as possible, so the untested part is small; it is checked by looking at it, or by a few slow end-to-end tests.
Comparing the three
Section titled “Comparing the three”| Question | MVC | MVP (passive view) | MVVM |
|---|---|---|---|
| Who handles input? | the controller | the view forwards to the presenter | the view writes properties, calls commands |
| Who formats what is shown? | the view formats the screen; the controller chooses the messages | the presenter | the view model |
| Does the view know the model? | yes, it reads it | no | no |
| Who calls the view? | the model’s observer, the controller | the presenter, through an interface | only its own bindings; the view model holds no reference to it |
| Tested without a screen? | the model only, or through the view’s output | the presenter, with a fake view | the view model, with no view |
| Extra machinery | an observer on the model | a view interface and a two-way link | observable properties and binding |
Where each fits
Section titled “Where each fits”- Desktop applications with a toolkit that has data binding, such as Qt’s QML or WPF: MVVM fits, because the toolkit does the binding, and the view model can be tested without the view, although it still uses the toolkit’s property and notification mechanism.
- Desktop or embedded screens without binding, such as widgets drawn by hand or a small LCD with a few buttons: MVP fits. The view interface can be a thin driver over the display, the presenter runs in host-side tests without the hardware, and nothing needs a property system.
- Toolkits built around widgets that observe data, and programs with several live views of one model, such as a chart and a table of the same numbers: MVC’s “views observe the model” is natural.
- Terminal programs that keep a screen up to date: MVP is a good default. It needs no property system, and the presenter is easy to test; MVVM is about as much code here, and as testable.
Common mistakes
Section titled “Common mistakes”- The model knows the screen. A
Course::print_roster()or a model that calls a view puts the words in the rules’ class, and a second screen must then change the model. The model should only announce that it changed. - A fat view. Checking ids or choosing messages in an MVP view or
an MVVM view moves logic back to the one place without tests. If a
view has an
ifabout the domain, it probably belongs in the presenter or view model. - A view model that holds a widget. Once the view model calls the view, it is MVP with extra steps, and its tests need a fake view.
- Forgetting the lifetime of observers. A view that subscribes and is destroyed without unsubscribing leaves the model calling freed memory. Hold the subscription as a member, last, and make the class neither copyable nor movable.
- Redrawing from the controller or presenter after each command,
instead of observing. Changes made elsewhere are then not shown
until the next command.
The example’s
a_change_made_elsewhere_still_redrawstest guards this. - Calling it MVC without saying which. As the callout above notes, the name covers several divisions; describe who knows whom.
When the requirements change
Section titled “When the requirements change”- A second screen of the same course, such as a seat counter. MVC adds a view that subscribes; MVP adds a presenter and a view; MVVM adds a view, and a count property or a small view model for it. The model does not change in any of them.
- A window replaces the terminal. In MVP, write a new class that
implements
mvp::RosterView; the presenter and its tests do not change. In MVVM, write a new view that binds to the same view model. In MVC, both the view and the controller are tied to the terminal, so both are rewritten. - The words are translated. All three call the
textfunctions by name, so a translatedscreen_text.cpp, chosen at build time, changes no screen class. Choosing the language at run time means passing the text functions in, which changes every constructor that uses them. The presenter’s and view model’s tests then check one language, or the ids of the messages. - The model changes on another thread, for example when a server
pushes an update.
ui::Signalis not thread-safe, and most toolkits allow drawing only on one thread. The change must be passed to the screen’s thread, typically through a queue the toolkit offers, and the observer called there. A planned page on threads covers safe hand-offs.
Exercise
Section titled “Exercise”Exercise: Test a presenter
Using the FakeView above, write two tests for
RosterPresenter::drop_requested:
- In a course of one seat with S1 seated and S2 waiting,
dropping S1 must show a new screen in which S2 is seated and no one
is waiting, and the message
S1 left CS101. - Dropping S7, who is not in the course, must show no new screen
and the message
S7 is not in CS101.
Then answer: why does the first test set up the roster before
calling start, and what would change if it did so after?
Show the explained answer
These tests are in the example and pass:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A one-seat course with S1 seated and S2 waiting, set up before start()// so those two changes are not recorded. Dropping S1 promotes S2: one new// screen (S2 seated, nobody waiting) and the message about S1.LLD_TEST(a_drop_that_promotes_shows_the_new_roster_and_who_left) { model::Roster roster{course(1)}; roster.enroll(student("S1")); roster.enroll(student("S2")); // waiting FakeView view; mvp::RosterPresenter presenter{roster, view}; presenter.start(); presenter.drop_requested("S1"); LLD_CHECK_EQ(view.screens.size(), std::size_t{2}); LLD_CHECK_EQ(view.screens[1][1], std::string{" seated: S2"}); LLD_CHECK_EQ(view.screens[1][2], std::string{" waiting: none"}); LLD_CHECK(view.messages == std::vector<std::string>{"S1 left CS101"});}
// S7 is in neither list, so the course answers not_in_course, the roster// announces nothing, and only the message appears.LLD_TEST(dropping_someone_absent_changes_nothing) { model::Roster roster{course(1)}; FakeView view; mvp::RosterPresenter presenter{roster, view}; presenter.start(); presenter.drop_requested("S7"); LLD_CHECK_EQ(view.screens.size(), std::size_t{1}); LLD_CHECK(view.messages == std::vector<std::string>{"S7 is not in CS101"});}The roster is set up before start, which is when the presenter
subscribes, so the setup’s two changes are not recorded: after start, the fake holds exactly one
screen, and the test’s checks are about the drop alone. If S1 and S2
were enrolled after start, the presenter would observe both changes
and the fake would hold three screens before the drop, so the test
would check screens[3] and screens.size() == 4. That still works,
but couples the test to setup it is not about.
The tests also never print anything, and need no terminal: that is what the view interface buys.
Summary
Section titled “Summary”- A screen’s code is state and rules, presentation logic, input handling, and drawing. All three patterns put the first in a model that knows no screen, and the last in a view.
- MVC: the view observes and reads the model and draws itself; a controller handles input.
- MVP: a presenter handles input and does all presentation logic; a passive view, behind an interface, shows what it is told. The presenter is tested with a fake view.
- MVVM: a view model holds the screen’s state as observable properties and offers commands, and never calls a view. It is tested with no view at all; binding is the cost.
- Observers keep a screen up to date even when someone else changes the model; in C++, hold the subscription as the last member and make the class neither copyable nor movable.
- For a program with no screen that stays open, none of them is needed.