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 NoneWhy 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.
| Who | Knows about | Does not know about |
|---|---|---|
| A classroom | Students | Grades |
| A student | Grades | The classroom |
Example 1 — a change in the grade’s representation
- The grade goes from simple to complex.
- Only the student knows what a grade is.
- So only it changes.
- The classroom keeps working.
Example 2 — why not to shortcut
- One could compute directly from the grades.
- That is shorter by one line.
- And costs a change in two classes.