Skip to content

Checkpoint: A Checked Transfer

The Course
•
35 min study

This checkpoint combines the day's three ideas in one small type. A transfer moves an amount of stock from one location to another. Each field can be wrong on its own, a zero ID or a zero amount, but one rule involves two fields at once: the source and the destination must differ. A rule like that cannot live in a validated field type such as Quantity, because neither field knows about the other. It belongs at the point where the whole value is checked, and the result should be a type that downstream code can trust without repeating the checks.

What you will use

  • A draft and a checked type. Draft has public fields for assembling input. Checked has private fields and is only produced by Draft::validate(self).
  • An error enum with context. TransferError has one variant per broken rule, carrying the offending value where there is one, and a Display message for each.
  • The Error trait. Implement std::error::Error so the error fits standard interfaces.
  • A read-only consumer. A summary method on Checked is the only way the rest of the program sees the fields.

Plan before you type

  1. Put Draft, Checked and TransferError in a transfers module, with Checked's fields private.
  2. Give TransferError the variants ZeroId, SameLocation(u32) and ZeroAmount, and derive Debug, PartialEq, Eq.
  3. Implement Display with a match, producing location IDs must be positive, cannot transfer from 4 to itself and amount must be positive.
  4. Write validate(self) -> Result<Checked, TransferError>, checking zero IDs first, then the shared rule, then the amount.
  5. In main, run one draft per rejected condition, assert the exact variant and print each message. Add two drafts that break two rules at once, to pin the order. Then validate one good draft and print its summary.
Prove each rule is checked

A draft that breaks exactly one rule, with every other field valid, proves that particular check exists: if a draft broke two rules, deleting one check would go unnoticed because the other would still reject it. But single-defect drafts cannot see the order of the checks. With one rule broken, every order gives the same answer. Order shows only when two rules are broken at once and the exact variant is asserted: (4, 4, 0) must report the same location, not the zero amount, and (0, 0, 5) must report the zero ID, not "from 0 to itself". Use one-defect drafts to prove each check exists, and a deliberate two-defect draft for each ordering you promise.

Mistakes worth checking for

  • (4, 4, 0) reports a zero amount instead of the same location: the checks run in a different order than planned, so decide the order deliberately and test it.
  • apply or summary can be called on a Draft: the consumer accepts the draft type, or Checked has public fields that let outside code build one.
  • The compiler rejects impl std::error::Error for TransferError {} with E0277: Display or Debug is missing.
  • unwrap_err() does not compile on the result: it prints the Ok value if it panics, so it needs Checked to implement Debug. Call .err() to get an Option of the error instead, or derive Debug on Checked if showing its fields is acceptable.
Exercise

Your turn

Write the transfers module as planned. Check the one-defect drafts (0, 2, 5), (1, 0, 5), (4, 4, 5) and (1, 2, 0) as source, destination and amount, then the two-defect drafts (0, 0, 5) and (4, 4, 0), asserting each variant and printing each error message. Then validate (1, 2, 5) and print its summary as 1 -> 2: 5.

Your working space Rust
fn main() {
    // Define Draft, Checked and TransferError inside a module, then check their boundary.
}
Hint 1: the idea

Validate the relationship between fields as well as each field. The same-location rule only makes sense once both IDs are known to be positive, so check it after the zero-ID rule.

Hint 2: a first step

Write the error enum and its Display first, and print one variant to see the message. Then start validate with the zero-ID rule as an early return; the fields move into Checked only after every check has passed.

Worked solution
Run the solution Rust
mod transfers {
    use std::fmt;

    pub struct Draft { pub from: u32, pub to: u32, pub amount: u32 }
    pub struct Checked { from: u32, to: u32, amount: u32 }

    #[derive(Debug, PartialEq, Eq)]
    pub enum TransferError {
        ZeroId,
        SameLocation(u32),
        ZeroAmount,
    }

    impl fmt::Display for TransferError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                TransferError::ZeroId => write!(f, "location IDs must be positive"),
                TransferError::SameLocation(id) => write!(f, "cannot transfer from {id} to itself"),
                TransferError::ZeroAmount => write!(f, "amount must be positive"),
            }
        }
    }
    impl std::error::Error for TransferError {}

    impl Draft {
        pub fn validate(self) -> Result<Checked, TransferError> {
            if self.from == 0 || self.to == 0 { return Err(TransferError::ZeroId); }
            if self.from == self.to { return Err(TransferError::SameLocation(self.from)); }
            if self.amount == 0 { return Err(TransferError::ZeroAmount); }
            Ok(Checked { from: self.from, to: self.to, amount: self.amount })
        }
    }
    impl Checked {
        pub fn summary(&self) -> String {
            format!("{} -> {}: {}", self.from, self.to, self.amount)
        }
    }
}

use transfers::{Draft, TransferError};

fn main() {
    let rejected = [
        ((0, 2, 5), TransferError::ZeroId),
        ((1, 0, 5), TransferError::ZeroId),
        ((4, 4, 5), TransferError::SameLocation(4)),
        ((1, 2, 0), TransferError::ZeroAmount),
        // Two rules broken at once: these pin the order of the checks.
        ((0, 0, 5), TransferError::ZeroId),
        ((4, 4, 0), TransferError::SameLocation(4)),
    ];
    for ((from, to, amount), expected) in rejected {
        let error = Draft { from, to, amount }.validate().err().expect("rejected");
        assert_eq!(error, expected);
        println!("({from}, {to}, {amount}): {error}");
    }
    let transfer = Draft { from: 1, to: 2, amount: 5 }.validate().unwrap();
    println!("{}", transfer.summary());
}
Text
(0, 2, 5): location IDs must be positive
(1, 0, 5): location IDs must be positive
(4, 4, 5): cannot transfer from 4 to itself
(1, 2, 0): amount must be positive
(0, 0, 5): location IDs must be positive
(4, 4, 0): cannot transfer from 4 to itself
1 -> 2: 5

The first four drafts each break one rule, so deleting any check makes its assertion fail. The last two break two rules each, so they are the ones that fail if the checks are reordered: move the amount check first and (4, 4, 0) reports ZeroAmount; move the same-location check first and (0, 0, 5) reports SameLocation(0). Without them, every order of the three ifs would print the same output. .err().expect(...) keeps Checked free of a Debug derive, which would otherwise be the only reason to add one. Notice that SameLocation(4) carries the ID, so the message can name it. On Day 4 a checked batch like this one is applied atomically to the ledger.

Was this article helpful?

Your response is saved on this device.