Grade 10 Computer Science · Objects
Common mistakes with objects
The wrong assumptions recurring in everyone learning this subject.
Code that runs perfectly, yet in the wrong place
A method inside a class always returns the right result, and no test fails. And still it is a mistake. How can code that works be wrong, and which one short question exposes it before it is even written?
The four mistakes below are not mistakes of carelessness. They come from “class” and “object” sounding alike, and from the syntax hiding part of what happens. Whoever recognises them once usually does not repeat them.
- Thinking a class holds the data — The class is a mould; the data lives in the objects. The test: create two objects and change one, the other will not change. That proves the data is not in the class.
- Skipping initialisation because “it will fill later” — The error will explode far from the place that caused it. Every field gets a value in the constructor, even an empty list. That turns an obscure bug into no bug.
- Putting code in a method that does not belong to the object — The class grows into a place that knows too much. The question: does the method use the object’s data? If not — it is an ordinary function in disguise.
- Touching internal fields because “it is only reading” — Reading creates a commitment exactly as writing does. If the value is needed outside, add a method returning it. Then the boundary stays where it is.