AlgoViz

IS-A and HAS-A

easy 40 min

IS-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. 1

    Version 1

    Employee extends Person, Customer extends Person. Clean on paper.

  2. 2

    Week 3

    Noor works here and buys here. Two objects for one person, with two addresses.

  3. 3

    Week 5

    Noor moves. One address is changed, parcels go to the old one.

  4. 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. 5

    The patch

    EmployeeCustomer extends ...: the explosion has begun.

A person holds roles

Person+ id: Id+ name: str- roles: List<Role>+ start(role)+ role(kind): Role?

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 = day

Lines 5 to 8

Dates are the reason for the class. A subclass of Person has no place for an end.

1 of 5

Role, subclass or flag?

ChooseWhenCost
SubclassFor life, exclusive, behaviour differsNo change, no combination
Role objectBegins, ends, combines, has its own dataOne more lookup
Flag or enumNo own data, hardly any behaviourGrows into switches
StateOne of several at a time, behaviour changesA class per state