IS-A and HAS-A
easy 40 minIS-A says that an object is a kind of something and can stand in for it.
Watch lesson4:45
Roles that change
Employee, customer, driver: what a person is today is not what a person is.
The point: if it has a start date or an end date, it is a role, and a role is held.
Failure walk
The employee who also buys
- 1
Version 1
Employee extends Person,Customer extends Person. Clean on paper. - 2
Week 3
Noor works here and buys here. Two objects for one person, with two addresses.
- 3
Week 5
Noor moves. One address is changed, parcels go to the old one.
- 4
Week 9
Noor leaves the company. The object is an Employee for ever, so it is deleted and Noor's orders point to nothing.
- 5
The patch
EmployeeCustomer extends ...: the explosion has begun.
A person holds roles
1/4One identity
One object per person for life: one id, one address.
owns (dies together)extends (is a)
Roles in code
One identity, many roles, at most one open role of a kind.
from __future__ import annotationsfrom dataclasses import dataclass, field@dataclassclass Role: since: int until: int | None = None@dataclassclass EmployeeRole(Role): salary: int = 0@dataclassclass CustomerRole(Role): points: int = 0@dataclassclass Person: name: str _roles: list[Role] = field(default_factory=list) def start(self, role: Role) -> None: if self.role(type(role)) is not None: raise ValueError(f"{self.name} already has {type(role).__name__}") self._roles.append(role) def role(self, kind: type[Role]) -> Role | None: return next((r for r in self._roles if isinstance(r, kind) and r.until is None), None) def end(self, kind: type[Role], day: int) -> None: role = self.role(kind) if role is None: raise LookupError(f"{self.name} has no {kind.__name__}") role.until = dayLines 5 to 8
Dates are the reason for the class. A subclass of Person has no place for an end.
Role, subclass or flag?
| Choose | When | Cost |
|---|---|---|
| Subclass | For life, exclusive, behaviour differs | No change, no combination |
| Role object | Begins, ends, combines, has its own data | One more lookup |
| Flag or enum | No own data, hardly any behaviour | Grows into switches |
| State | One of several at a time, behaviour changes | A class per state |