Skip to content

Checkpoint: Validate Before You Change State

The Course
•
28 min study

A function that rejects bad input has two jobs: give the right answer, and leave everything else untouched when it says no. A version that pushes first and checks afterward can return false and still have stored the bad value, and a test that only looks at the return value would never notice. In this checkpoint the checks are already written. They fail on the starter, because its add rejects everything. Your job is to make them pass, then prove they would catch a wrong version.

What you will use

  • A mutable borrow. add takes &mut Vec<u32>, so it can push into a vector that main owns.
  • A range condition. minutes >= 1 && minutes <= 240 is true only inside the allowed range.
  • Check before change. The push happens only on the path where the condition is true.
  • assert_eq! on results and on state. Each call's bool is checked, and so is the whole vector at the end.

Plan before you type

  1. Run the starter and read which assertion fails first, and its left and right values.
  2. In add, write an if with the range condition.
  3. In the true branch, push and return true. In the false branch, return false without touching the vector.
  4. Run until Session checks passed appears.
  5. Break the rule on purpose, as described below, and restore it.

Reading a failed run is part of the plan, not a detour. The first time you press Run, the starter stops at the very first assertion, add(&mut durations, 240), with left: false and right: true. left is what the function actually returned and right is what the check expected. Because a run stops at its first failure, the later checks have not run yet; each fix you make lets the program get one step further.

Look at the order of the checks, too. The accepted 240 comes first, then two rejections, then the accepted 1, and the vector comparison comes last. That last line can only pass if every earlier call did exactly the right thing to the vector: 240 and 1 stored, in that order, and nothing else. It is a single assertion that summarizes the whole history of the state.

Prove the checks can fail

Change the condition to minutes <= 240, which accepts zero. The add(&mut durations, 0) check now fails with left: true and right: false. Restore it, then move the push above the if so every value is stored. This time the returns are all correct, and only the final assert_eq!(durations, ...) catches the problem. That last check is the reason the checkpoint compares the whole vector.

Mistakes worth checking for

  • mismatched types: expected bool, found (): a branch ends with true; instead of true. The semicolon turns the value into a statement, so the branch produces nothing.
  • The 240 check fails: the condition uses < 240, leaving out the upper boundary.
  • The 1 check fails: the condition uses > 1 instead of >= 1.
  • Every return is right but the final vector holds 0 or 241: the push happens before or outside the check.
Exercise

Your turn

Implement add so it stores durations from 1 through 240 and returns true. For any other duration, return false and leave the vector unchanged. Run the visible cases until all pass. Then change the condition to accept zero and identify the assertion that fails.

Your working space Rust
fn add(sessions: &mut Vec<u32>, minutes: u32) -> bool {
    // Validate minutes before pushing.
    false
}

fn main() {
    let mut durations = vec![25];
    assert_eq!(add(&mut durations, 240), true);
    assert_eq!(add(&mut durations, 0), false);
    assert_eq!(add(&mut durations, 241), false);
    assert_eq!(add(&mut durations, 1), true);
    assert_eq!(durations, vec![25, 240, 1]);
    println!("Session checks passed");
}
Hint 1: the idea

Check the duration before mutating the vector. Then the rejection path cannot store anything.

Hint 2: a first step

Use an if condition that includes both ends of the allowed range, joined with &&.

Worked solution
Run the solution Rust
fn add(sessions: &mut Vec<u32>, minutes: u32) -> bool {
    if minutes >= 1 && minutes <= 240 {
        sessions.push(minutes);
        true
    } else {
        false
    }
}

fn main() {
    let mut durations = vec![25];
    assert_eq!(add(&mut durations, 240), true);
    assert_eq!(add(&mut durations, 0), false);
    assert_eq!(add(&mut durations, 241), false);
    assert_eq!(add(&mut durations, 1), true);
    assert_eq!(durations, vec![25, 240, 1]);
    println!("Session checks passed");
}
Text
Session checks passed

The return checks verify each decision; the final comparison verifies exactly what survived those decisions, in order. assert_eq! can compare two vectors directly because it compares them item by item. The study planner's add_line follows the same rule: every check runs before the single push at the end.

Was this article helpful?

Your response is saved on this device.