Skip to content

Validate Before Committing

The Course
•
35 min study

An edit may replace several related fields at once: "rename task 2 to Review and set it to 10 minutes". Suppose the function assigns the title, then checks the minutes, finds them invalid and returns an error. The caller is told the edit failed, yet the task now has the new title with the old duration. That half-applied edit is worse than a clean failure: the caller believes nothing changed, the data says otherwise, and no single field looks wrong.

The rule that prevents it is short: validate every proposed value first, then change the object. A rejected edit then leaves the object exactly as it was, and an accepted edit changes all the requested fields. There is no third outcome. This lesson also shows why the project takes the new title by value and moves it in.

Predict and run

The new duration is 0, so the edit is rejected. What is printed?

Predict before running C++
#include <iostream>
#include <string>
#include <utility>

struct Record { std::string title; int minutes; };

bool edit(Record& record, std::string title, int minutes) {
    if (title.empty() || minutes < 1 || minutes > 180) { return false; }
    record.title = std::move(title);
    record.minutes = minutes;
    return true;
}

int main() {
    Record record{"Read",25};
    bool ok = edit(record, "Changed", 0);
    std::cout << ok << " " << record.title << " " << record.minutes << "\n";
    return 0;
}
Check your prediction
Text
0 Read 25

The single guard checks both fields before either assignment runs, so the rejected call leaves "Read" and 25. "Changed" was a valid title, but validity of each field alone is not the point: the edit is one request, and it is accepted or rejected as a whole.

Before and after: interleaved checks

Here is the tempting version, which checks each field just before assigning it, next to the correct one:

Half-applied versus all-or-nothing C++
#include <iostream>
#include <string>
#include <utility>

struct Record { std::string title; int minutes; };

bool edit_interleaved(Record& record, std::string title, int minutes) {
    if (title.empty()) { return false; }
    record.title = std::move(title);
    if (minutes < 1 || minutes > 180) { return false; }
    record.minutes = minutes;
    return true;
}

bool edit_checked(Record& record, std::string title, int minutes) {
    if (title.empty() || minutes < 1 || minutes > 180) { return false; }
    record.title = std::move(title);
    record.minutes = minutes;
    return true;
}

int main() {
    Record a{"Read", 25};
    Record b{"Read", 25};
    const bool first = edit_interleaved(a, "Review", 0);
    const bool second = edit_checked(b, "Review", 0);
    std::cout << "interleaved: " << first << " " << a.title << " " << a.minutes << "\n";
    std::cout << "checked: " << second << " " << b.title << " " << b.minutes << "\n";
    return 0;
}
Text
interleaved: 0 Review 25
checked: 0 Read 25

Both functions return false, so a test that only checks the return value passes for both. The difference is only visible in the whole state after the call, which is why the project's tests compare the full export before and after a rejected edit.

Make the commit step unable to fail

Validate-then-commit works only if the commit itself cannot fail halfway. Assigning an int or an enum cannot fail. Copying a std::string can, in principle, because it may need to allocate memory. Moving one does not allocate: it takes over the parameter's buffer. So the project's edit takes the title by value and moves it in:

  • The parameter owns a candidate. A caller passing a variable gets a copy made at the call, before any check; a caller passing a temporary like "Review" builds it directly in the parameter.
  • Validation reads the candidate. Nothing in the object has changed yet.
  • The commit moves. title_ = std::move(title); hands over the buffer, and the following assignments are plain integers.

After std::move(title), the parameter is in a valid but unspecified state, so the function must not read it again. Validating before the move is what keeps that safe.

This promise, called the strong guarantee for domain errors, covers rejected input. It does not promise anything if memory runs out while the caller's string is being copied into the parameter; that is outside the course's recovery contract.

Practice

Exercise

Your turn

Write a Task class with private title_, minutes_ and done_, a constructor, a std::string describe() const that returns text such as Read (25, todo), and bool edit(std::string title, int minutes, bool done) that accepts titles of 1 through 40 characters and minutes of 1 through 180. Starting from Read, 25, not done, try three edits and print each result and the state:

Text
edit "" 10 done: rejected, Read (25, todo)
edit "Review" 181 done: rejected, Read (25, todo)
edit "Review" 10 done: ok, Review (10, done)
Your workspace C++
#include <iostream>
#include <string>
#include <utility>

// Write Task here.

int main() {
    // Task task("Read", 25, false);
    return 0;
}
Hint 1: the idea

No field may change before every check passes. Write one guard that covers all the rules, and put every assignment after it.

Hint 2: a first step

Write the constructor and describe first and print the starting state: Read (25, todo). Then write edit with the guard alone, returning false when any rule fails and true otherwise, with no assignments yet. Run the three edits: the first two should report rejected. Only then put the assignments after the guard.

Show one solution
Run the solution C++
#include <iostream>
#include <string>
#include <utility>

class Task {
public:
    Task(std::string title, int minutes, bool done)
        : title_(std::move(title)), minutes_(minutes), done_(done) {}
    bool edit(std::string title, int minutes, bool done) {
        if (title.empty() || title.size() > 40 || minutes < 1 || minutes > 180) { return false; }
        title_ = std::move(title);
        minutes_ = minutes;
        done_ = done;
        return true;
    }
    std::string describe() const {
        return title_ + " (" + std::to_string(minutes_) + ", " + (done_ ? "done" : "todo") + ")";
    }
private:
    std::string title_;
    int minutes_;
    bool done_;
};

void attempt(Task& task, const std::string& title, int minutes) {
    const bool ok = task.edit(title, minutes, true);
    std::cout << "edit \"" << title << "\" " << minutes << " done: "
              << (ok ? "ok" : "rejected") << ", " << task.describe() << "\n";
}

int main() {
    Task task("Read", 25, false);
    attempt(task, "", 10);
    attempt(task, "Review", 181);
    attempt(task, "Review", 10);
    return 0;
}
Text
edit "" 10 done: rejected, Read (25, todo)
edit "Review" 181 done: rejected, Read (25, todo)
edit "Review" 10 done: ok, Review (10, done)

Each rejected edit had at least one valid field (10 minutes, then the title "Review"), and neither leaked into the task, which proves the guard covers all fields before any assignment. attempt passes title as a named variable, so edit receives a copy and can move from it freely while the caller's string stays intact. The checkpoint next tests these promises on a whole collection by comparing exported state.

Was this article helpful?

Your response is saved on this device.