Model Value Objects and Typed Outcomes
Core idea
A value object represents a domain value by its content, not by an external identity. Validate its constraints on construction, and prefer immutable component types if it must remain unchanged. A union of explicit success and failure records makes expected domain outcomes distinguishable from unexpected exceptions.
from dataclasses import dataclass@dataclass(frozen=True)class Quantity: units:int def __post_init__(self): if type(self.units) is not int or self.units<0: raise ValueError('nonnegative integer required') def plus(self,other:'Quantity')->'Quantity': return Quantity(self.units+other.units)print(Quantity(3).plus(Quantity(4))==Quantity(7))Equality is content-based. plus constructs a new validated value; bool is deliberately excluded.
Return an explicit outcome
from dataclasses import dataclass@dataclass(frozen=True)class Reserved: remaining:int@dataclass(frozen=True)class Rejected: reason:strdef reserve(stock:int,requested:int)->Reserved|Rejected: if stock<0 or requested<=0: return Rejected('invalid quantity') if requested>stock: return Rejected('insufficient stock') return Reserved(stock-requested)for n in (3,9): result=reserve(5,n) if isinstance(result,Reserved): print(result.remaining) else: print(result.reason)Callers branch on a named result type and can access its specific field; the function assumes integer inputs.
Common mistake
Do not use a magic integer such as -1 to mean every failure when reasons matter. Do not silently catch unrelated exceptions; validate at external boundaries and keep unexpected errors distinct.
Practice
Model a bounded seat count with a frozen record, and a booking result with accepted and rejected records. Test zero, exact capacity and excess requests.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Value objects and typed results
Check your understanding of value objects and typed results.
What is printed?
from dataclasses import dataclass@dataclass(frozen=True)class Count: n:inta=Count(2);b=Count(2)print(a==b,a is b)What is printed?
from dataclasses import dataclass@dataclassclass Ok: value:int@dataclassclass Err: reason:strr=Err("missing")print(r.value if isinstance(r,Ok) else r.reason)What makes a value object valid?
Why return a union of named success and failure records?