AlgoViz

Class design: state and behaviour

medium 40 min

A requirement becomes something a class must remember, something it must do, or a rule it must keep.

Watch lesson4:41

Where it shows up

The same pattern appears across everyday software.

  • Java BlockingQueue

    Four method families for one situation: `add` throws, `offer` returns false, `put` waits, and a timed `offer` gives up. The name tells you how it says no.

  • Java LocalDate

    An immutable date. There is no setter: `plusDays` answers with a new date, so a wrong month can never appear later.

  • Python datetime

    The constructor of `date` raises `ValueError` outside the allowed ranges. An object with day 31 of April cannot exist.

  • PostgreSQL check constraints

    A rule such as price above zero is written beside the column. Every program that writes to the table must keep it.

  • Stripe PaymentIntent

    One object with a status that moves through named steps, such as requires_payment_method. The documentation describes the whole life of the object.

  • Kubernetes objects

    An object separates `spec`, which the user sets as desired state, from `status`, which the system writes. Two facts, two owners.

  • Rust NonZero

    A type for a number that is known not to be zero. The check happens once, when the value is made.

  • GitHub merge API

    Merging a pull request answers 405 if it cannot be merged and 409 if the head has moved. Two reasons to refuse, two different codes.

  • Java Iterator

    `remove` raises IllegalStateException if `next` has not been called. A call in the wrong order is refused with a named error.