Grade 10 Computer Science · Objects

Objects that hold objects

How a structure is built from several classes without mixing responsibility.

Tomorrow a grade will no longer be a number

Suppose that tomorrow every grade becomes an object with a weight and a date. How many classes in the program will have to change? The answer depends on one line you write today, one that looks like a harmless shortcut.

One class suffices exactly until it stops sufficing. A class holds students, a student holds grades, a grade belongs to a subject — and the moment one tries to squeeze it all into a single class one gets exactly what we fled from: one place that knows everything, so every change touches it.

class Classroom:
    def __init__(self, name):
        self.name = name
        self.students = []

    def enrol(self, student):
        self.students.append(student)

    def average(self):
        marks = [s.average() for s in self.students if s.average() is not None]
        return sum(marks) / len(marks) if marks else None

Why this pays

Suppose tomorrow grades stop being numbers and become objects with a weight and a date. Had the class computed the average directly from the grade list, it would have to change. In this structure only the student changes — the only one who knows what a grade is — and the class keeps working untouched. This is the same return abstraction promised, and here it comes from the division of responsibility rather than the name.

WhoKnows aboutDoes not know about
A classroomStudentsGrades
A studentGradesThe classroom

Example 1 — a change in the grade’s representation

  1. The grade goes from simple to complex.
  2. Only the student knows what a grade is.
  3. So only it changes.
  4. The classroom keeps working.

Example 2 — why not to shortcut

  1. One could compute directly from the grades.
  2. That is shorter by one line.
  3. And costs a change in two classes.
Instead of walking all the way to the grade, ask the neighbor for the answer: s.average().