Grade 10 Computer Science · Objects

What to keep inside

The boundary between what the object promises and how it does it.

Nobody is breaking in, so why hide anything?

Nobody is trying to break your code, and Python does not block access to any field at all. And still programmers mark fields as internal and ask others not to touch them, not even just to read. What exactly are they guarding against?

Every object has two parts: what may be touched from outside, and what belongs to it alone. This boundary is not protection against malice — no one is trying to break your code. It is protection against reliance: the moment someone outside touches an internal field, that field becomes part of the promise, and it can no longer be changed.

class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius        # internal

    def celsius(self):
        return self._celsius

    def fahrenheit(self):
        return self._celsius * 9 / 5 + 32

What the boundary buys

In the example only one Celsius value is kept, and Fahrenheit is computed at each call. One could have chosen the reverse, or kept both. As long as no one outside touches the internal field, that decision stays yours forever — and if converting at each call turns out too expensive, you can keep both without a single line of outside code knowing anything happened.

What is visibleWhat is internal
What the object promisesHow it keeps it
Hard to changeEasy to change
People rely on itNo one knows about it

Example 1 — a decision left open

  1. Only one unit is kept.
  2. The second is computed at each call.
  3. This can be swapped without breaking anyone.

Example 2 — reliance that closes options

  1. Outside code reads the internal field.
  2. Now it is part of the promise.
  3. And any change to it breaks code.
A scenario: The weather report — at each step a course of action is chosen and its consequence shown; 5 possible situations.