Divide responsibilities between objects

Lesson 12 of 19 · Python Object Design

When an operation involves several objects, decide which object owns each rule. The coordinator can ask another object to act instead of editing that object’s internal state.

program -> Enrollment.enroll(name)
               |-- asks Roster to add the name
               +-- returns the resulting size
class Roster:
    def __init__(self):
        self._names = []

    def add(self, name):
        if not isinstance(name, str) or not name:
            raise ValueError("name required")
        self._names.append(name)

    def size(self):
        return len(self._names)

class Enrollment:
    def __init__(self, roster):
        self._roster = roster

    def enroll(self, name):
        self._roster.add(name)
        return self._roster.size()

roster = Roster()
enrollment = Enrollment(roster)
print(enrollment.enroll("Mina"))
print(enrollment.enroll("Omar"))
try:
    enrollment.enroll("")
except ValueError as error:
    print(error)
print(roster.size())

Output:

1
2
name required
2

Roster owns validation and its list; Enrollment coordinates calls. Here the coordinator keeps a reference to a separately created roster. This is composition in the broad design sense: one object uses another as a part of its behavior. It is also delegation: Enrollment asks the roster to perform work. The roster can be shared elsewhere; storing a reference does not copy it.

On invalid input, add raises before changing the list, so size is never called for that request. In a more complex sequence, one collaborator might succeed and a later one fail. A clear contract must explain partial changes or arrange an appropriate rollback; splitting responsibilities does not automatically make a multi-object operation atomic.

Chapter contents