Skip to content

Check a Contract

The Course
•
35 min study

So far you have checked programs by reading their output and comparing it with a prediction. That works for one run, but it does not scale: after every change you would have to reread every line and remember what each number should be. An automatic check writes the expected answer into the program itself. If the code ever stops matching the expectation, the program tells you immediately.

assert from <cassert> checks a Boolean expression. When the expression is true, execution continues silently. When it is false, the program prints a message naming the failed expression, its file and line, and stops at once. A function's contract is the promise it makes, such as "returns true for 1 through 180 and false otherwise." Assertions turn that promise into something you can run.

Predict and run

Predict before running C++
#include <iostream>
#include <cassert>

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

int main() {
    assert(valid_minutes(1));
    assert(valid_minutes(180));
    assert(!valid_minutes(0));
    assert(!valid_minutes(181));
    std::cout << "Checks passed\n";
    return 0;
}
Check your prediction
Text
Checks passed

All four assertions were true, so the program reached the final line. Passing checks are silent on purpose: the only output that matters is either one confirmation at the end or the first failure.

What a failure looks like

Change >= 1 to > 1 in valid_minutes and run again. The first assertion is now false, and the program stops before printing anything:

Shell
main.cpp:9: int main(): Assertion `valid_minutes(1)' failed.
Aborted

The exact wording differs between compilers and between this browser and a local machine, but three things are always there: the expression that failed, where it is, and the fact that the run ended abnormally. "Checks passed" never appears, so you cannot miss the failure. Restore >= 1 before moving on.

Choose cases that can catch mistakes

An assertion is only as good as the case it checks. assert(valid_minutes(25)) passes for the correct function, and it also passes if you write > instead of >=, < instead of <=, or || instead of &&. It proves almost nothing. Good cases sit on the edges of the contract: each boundary, and the value just beyond it.

Choose the expected answer independently of your implementation. Work it out from the brief, by hand, before you write the function. If you run the function first and copy its output into an assertion, the assertion only proves that the code agrees with itself, bugs included.

Boundary cases for a helper C++
#include <iostream>
#include <cassert>

int remaining(int goal, int done) {
    if (done >= goal) {
        return 0;
    }
    return goal - done;
}

int main() {
    assert(remaining(60, 0) == 60);    // nothing done yet
    assert(remaining(60, 59) == 1);    // just below the goal
    assert(remaining(60, 60) == 0);    // exactly at the goal
    assert(remaining(60, 61) == 0);    // just past the goal
    std::cout << "Remaining checks passed\n";
    return 0;
}
Text
Remaining checks passed

Each comment names the reason the case exists. If someone deletes the if, the last assertion fails because 60 - 61 is -1. If someone writes done > goal, the exact-goal case still returns 0 by subtraction, so it passes, which tells you that the third case alone cannot detect that change. Thinking this way, "which mistake does this case catch?", is how you build a small but sharp set of tests.

Assertions are for programmers, not users

Assertions check that your code keeps its promises. They are not a way to reject bad input from a person or a file. A build can define NDEBUG, which removes every assert from the program, and then the check is simply gone. For that reason the planner rejects bad input with ordinary if statements and keeps assertions in its test program, which is always built with assertions enabled.

That removal also means an assertion must never do necessary work. assert(add_task(tasks, task)); would add the task only when assertions are on. Do the work first, store the result, then assert on the stored result.

Practice

Exercise

Your turn

Write int hours_rounded_up(int minutes) that returns how many whole hours you must book for a session: 0 minutes needs 0 hours, 1 through 60 minutes need 1 hour, 61 through 120 need 2, and so on. Assert at least these cases: 0 gives 0, 1 gives 1, 60 gives 1, 61 gives 2 and 120 gives 2. When they all pass, print Rounding checks passed.

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

int main() {
    // Write your function above main and your assertions here.
    return 0;
}
Hint 1: the idea

Integer division throws away the remainder, but a partial hour must count as a whole one. Either look at the remainder (minutes % 60) to decide whether one more hour is needed, or shift minutes up before dividing, by just enough that every partial hour crosses into the next whole number while an exact hour does not.

Hint 2: a first step

Write the five assertions first, with answers worked out by hand, and run them against a function that just returns minutes / 60. Note which cases fail and why.

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

int hours_rounded_up(int minutes) {
    return (minutes + 59) / 60;
}

int main() {
    assert(hours_rounded_up(0) == 0);
    assert(hours_rounded_up(1) == 1);
    assert(hours_rounded_up(60) == 1);
    assert(hours_rounded_up(61) == 2);
    assert(hours_rounded_up(120) == 2);
    std::cout << "Rounding checks passed\n";
    return 0;
}
Text
Rounding checks passed

Adding 59 turns any remainder from 1 to 59 into one extra whole hour, while an exact multiple of 60 gets only 59 extra minutes, which integer division discards. The plain minutes / 60 fails at 1 and 61, and minutes / 60 + 1 fails at 0 and 60: each wrong version is caught by a different edge. In the checkpoint you will write a function and its tests from a contract alone.

Was this article helpful?

Your response is saved on this device.