Skip to content

When a Record Needs Rules

The Course
•
35 min study

Beginner C++ taught strings, vectors, functions, references, records, automatic cleanup and stream parsing. Intermediate C++ asks a harder question: how does a larger program keep its promises when many functions can change the same data? C is not a prerequisite.

Picture a task tracker where every task has a duration in minutes. The weekly report adds the durations of unfinished tasks. If one part of the program stores -30 or 0 in a task, the report quietly prints a wrong total, and the bug shows up far from the line that caused it. You cannot fix that by being careful in the report. You fix it by deciding what a valid task is and making sure no task can exist without meeting that rule.

That rule is called an invariant: a statement that is true about an object whenever ordinary code can look at it. For this course's tracker, a task's duration is 1 through 180 minutes, its ID is positive, and its title is not empty. Over the next seven days you will build that tracker with stable IDs, validated edits and tested reports. Today starts with the rules themselves.

Predict and run

The function below is the duration rule written once. What does the program print for 25? What would it print for 0?

Predict before running C++
#include <iostream>

bool valid(int minutes) { return minutes >= 1 && minutes <= 180; }

int main() {
    int duration = 25;
    if (valid(duration)) { std::cout << "Accepted\n"; }
    return 0;
}
Check your prediction
Text
Accepted

25 is inside the range, so the condition is true. For 0 the program prints nothing at all, because there is no else. Change duration to 0, 1, 180 and 181 and check each prediction. The two values just inside the range (1 and 180) and the two just outside (0 and 181) are the boundary cases. Most range bugs, such as writing > where >= was meant, only show up there.

A check is not a guarantee

A checking function only helps where somebody remembers to call it. The record below is a plain struct with public fields. Both tasks are checked and accepted, and then a later line changes a field directly.

Valid once, invalid later C++
#include <iostream>
#include <string>

bool valid(int minutes) { return minutes >= 1 && minutes <= 180; }

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

int main() {
    Task read{"Read", 25};
    Task review{"Review", 10};
    if (valid(read.minutes) && valid(review.minutes)) { std::cout << "Both accepted\n"; }
    review.minutes = -30; // Nothing stops this assignment.
    std::cout << "Total: " << read.minutes + review.minutes << "\n";
    return 0;
}
Text
Both accepted
Total: -5

Nothing in the language objects to review.minutes = -30, because a public int field accepts any int. The check ran at the right moment, and the data still went wrong afterward. In a real program the bad assignment might be in another file, written months later by someone who never saw valid.

A public struct is the right tool when its fields really are independent. A point with x and y, where every pair of numbers is a valid point, needs no protection. Once a field has a rule, or two fields must agree with each other, the type itself has to control every change. The next lesson does that with a class and private members.

Write the contract before the code

A contract lists what a type accepts, what it rejects, and what happens when something is rejected. Writing it first keeps you from inventing rules in the middle of an if statement. For a task duration:

  • Valid: 1, 25 and 180.
  • Invalid: 0, -5 and 181.
  • Boundaries to test: 0, 1, 180 and 181.
  • On rejection: nothing changes. A rejected edit leaves the task exactly as it was.

The last line matters more than it looks. If "change the title and duration" can fail halfway, the task ends up with a new title and an old duration, a combination nobody asked for. Day 4 builds edits that validate everything first and then commit.

A list of cases also gives you tests for free. The program below runs the rule against every boundary at once, so a wrong comparison shows up as a wrong line.

Test the boundaries together C++
#include <iostream>

bool valid(int minutes) { return minutes >= 1 && minutes <= 180; }

int main() {
    const int cases[] = {0, 1, 25, 180, 181, -5};
    for (int minutes : cases) {
        std::cout << minutes << (valid(minutes) ? " valid" : " rejected") << "\n";
    }
    return 0;
}
Text
0 rejected
1 valid
25 valid
180 valid
181 rejected
-5 rejected

Change >= to > in valid and run again. Only the line for 1 changes. That is why the boundary cases belong in every test you write this week: they are the inputs that tell a correct rule from an almost correct one.

Practice

Exercise

Your turn

Write bool valid_title(const std::string& title) that accepts titles of 1 through 40 characters. Test it on the empty string, "Read", a 40-character string and a 41-character string (build those with std::string(40, 'x')). Print one line per case, then a final line:

Text
0 chars: rejected
4 chars: valid
40 chars: valid
41 chars: rejected
Title checks passed

Use assert from <cassert> to check each result as well as printing it.

Your workspace C++
#include <cassert>
#include <iostream>
#include <string>

// Write valid_title here.

int main() {
    // Check "", "Read", 40 and 41 characters.
    return 0;
}
Hint 1: the idea

The rule has two parts: the title must not be empty, and its length must not exceed 40. State both in one function so every caller uses the same rule.

Hint 2: a first step

title.empty() and title.size() read the string without changing it, which is why the parameter can be a const reference. Write a small report helper that prints title.size() and the result, so the four cases do not repeat the same print code.

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

bool valid_title(const std::string& title) {
    return !title.empty() && title.size() <= 40;
}

void report(const std::string& title) {
    std::cout << title.size() << " chars: " << (valid_title(title) ? "valid" : "rejected") << "\n";
}

int main() {
    const std::string empty;
    const std::string longest(40, 'x');
    const std::string too_long(41, 'x');
    assert(!valid_title(empty));
    assert(valid_title("Read"));
    assert(valid_title(longest));
    assert(!valid_title(too_long));
    report(empty);
    report("Read");
    report(longest);
    report(too_long);
    std::cout << "Title checks passed\n";
    return 0;
}
Text
0 chars: rejected
4 chars: valid
40 chars: valid
41 chars: rejected
Title checks passed

The 40- and 41-character cases are the boundary pair: writing < 40 instead of <= 40 would fail the third assertion. The const std::string& parameter lets the function read a caller's string without copying it and promises not to change it. The function still cannot stop someone from storing a bad title in a public field, which is the problem the next lesson solves with private members.

Was this article helpful?

Your response is saved on this device.