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.

An object is a joining of what is known and what can be done with it.
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 objectWith an object
The data in a dictionary, the operation in another fileBoth in one place
Every caller needs to know the rulesThe rules are enforced inside
The empty case is written again and againWritten once

Example 1 — what is kept in one place

  1. The computation is identical to an ordinary function.
  2. But it sits beside the data.
  3. So the empty case is written once.
  4. And every use gets it for free.

Example 2 — what is seen at a glance

  1. One file holds all the operations.
  2. Reading it answers what is permitted.
  3. Without searching in other files.
Whoever uses the object need not remember the empty case: it is already written inside.