Grade 10 Computer Science · Objects
Data that knows what is done with it
Why it is worth joining a value to the operations on it.
Five places that work out the same average
A program has five places that work out a student’s average, and each must remember what to do when there are no grades yet. Four remember, one forgot. How do you write that rule once, so that nobody can forget it again?
Until now data and operations lived apart: a dictionary held the student’s details, and a function in another file knew how to compute their average. That works, and it has a price that shows up only when the program grows. The operation sits far from the data it touches, so no one sees at a glance what may be done with this information and what may not.
class Student:
def __init__(self, name):
self.name = name
self.grades = []
def add(self, grade):
self.grades.append(grade)
def average(self):
if not self.grades:
return None
return sum(self.grades) / len(self.grades)What actually changed
Note that the computation itself is identical to the function you would have written anyway. What changed is who holds it. When the average lives inside the class, the question “what happens when there are no grades” is answered once, in the place where the data lives — and not everywhere someone wants an average. That is exactly the difference between code that repeats itself and code with one source of truth.
| Without an object | With an object |
|---|---|
| The data in a dictionary, the operation in another file | Both in one place |
| Every caller needs to know the rules | The rules are enforced inside |
| The empty case is written again and again | Written once |
Example 1 — what is kept in one place
- The computation is identical to an ordinary function.
- But it sits beside the data.
- So the empty case is written once.
- And every use gets it for free.
Example 2 — what is seen at a glance
- One file holds all the operations.
- Reading it answers what is permitted.
- Without searching in other files.