DevPath
Mid lesson · 12 min

Use small objects to protect invariants

Move a repeated rule into a value that can validate itself.

Find the invariant

If several controllers compute a booking interval or a money amount, the same validation will drift. A small immutable value object can require end after start and expose meaningful operations. It should reject invalid construction early rather than allow a partially valid object to travel through the application.

Keep the API narrow

A value object needs only the operations its callers use. Avoid a broad wrapper that simply mirrors every array access. Give methods names that express the rule, such as overlaps or durationMinutes. Normalize input before construction so the object does not have to guess whether a string means an integer.

final class Interval {
    public function __construct(public int $start, public int $end) {
        if ($end <= $start) throw new InvalidArgumentException('Invalid interval');
    }
}

Test edge cases

Test equal endpoints, reversed endpoints, touching intervals, and true overlap. A half-open interval convention can make adjacent bookings non-overlapping; document that convention. Make sure serialization or database hydration does not bypass the invariant in places where the object is reused.

Check your understanding

What should happen when an Interval is constructed with equal start and end values?

Show explanation

Construction should reject it if the domain requires a positive-length interval, so invalid state cannot circulate.

Put this lesson into practice

A practice activity at this level in the same module.

Try: Extract business logic from a fat controller

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.