Always Valid

Ensures the validity of an object at construction

Values rarely are simple integers, strings, or even dates. They often have requirements.

  • An e-mail address must have a specific format

  • A birthday cannot be in the future

  • A duration cannot be negative

Instead of carrying these validations outside of the objects, we can insist upon the objects being created if and only if the values are valid.

class Duration {
    constructor(private readonly value: number) {
        if (this.value < 0) {
            throw new Error("value can't be negative");
        }
    }
}

Last updated