Object or function? Choosing the clearer design
Converting degrees to radians, modelling a robot arm with three motors, parsing one line of a CSV file: which of these deserves a class?
About 30 min · 3 goals · Checked by automated tests
1.Why should I care?
Classes are a tool, not a goal. A good engineer reaches for one when data and behaviour belong together and there's state to protect, and writes a plain function when the job is just input → output. Choosing well keeps code short and obvious.
- ◇ Decide whether a task is clearer as a class or as plain functions, and justify it.
- ◇ Use composition: build an object from other objects (a robot that has motors).
- ◇ Represent a grid map as a class with a small, testable interface.
2.Predict
Which of these is the best candidate for a class?
Guess first. Being wrong here is how the surprise works.
3.Understand
Signs that you want a class
Several functions all take the same bundle of data; there's a rule the data must keep; you need many copies with their own state; or you want to swap one implementation for another behind the same methods (two kinds of sensor with the same read()).
Signs that a function is enough
The task is a calculation from inputs to an output with no memory between calls: unit conversions, a mean, a distance between two points. Wrapping these in a class adds ceremony and hides nothing worth hiding.
Composition: objects made of objects
A Robot can have a list of Motor objects and a RangeSensor. Each part keeps its own rules; the robot coordinates them. This 'has-a' structure mirrors real machines and is usually simpler than deep inheritance.
Explain it another way
A calculator button is a function: press it, get an answer. A thermostat is an object: it remembers a setpoint and the current temperature, and its buttons change that memory.
Classes bundle state with behaviour and give you a namespace, encapsulation and polymorphism (different classes, same method names). Their cost is indirection. Pure functions are easiest to test because the same inputs always give the same output.
Path-planning libraries usually model the map as an object (it has state and a query interface) but the search algorithms as functions that take the map as a parameter, so one planner works on any map that provides neighbours() and cost().
Worked example 1
A grid map class with a small interface that a planner can use.
class GridMap:
"""A rectangular map. '#' is a wall; any other character is free floor."""
def __init__(self, rows):
if not rows or any(len(r) != len(rows[0]) for r in rows):
raise ValueError("rows must be non-empty and equal in length")
self.rows = rows
self.height = len(rows)
self.width = len(rows[0])
def in_bounds(self, cell):
r, c = cell
return 0 <= r < self.height and 0 <= c < self.width
def is_wall(self, cell):
r, c = cell
return self.rows[r][c] == "#"
def neighbours(self, cell):
"""Free cells up, right, down and left of cell, in that order."""
r, c = cell
steps = [(r - 1, c), (r, c + 1), (r + 1, c), (r, c - 1)]
return [n for n in steps if self.in_bounds(n) and not self.is_wall(n)]
grid = GridMap(["..#",
"...",
"#.."])
print(grid.neighbours((0, 0))) # [(0, 1), (1, 0)]
print(grid.neighbours((1, 1))) # [(0, 1), (1, 2), (2, 1), (1, 0)]The map hides how cells are stored. A planner only needs neighbours, so you could later store the map as a set of wall coordinates without touching the planner.
Common mix-ups
- Professional code puts everything in classes.
✓ Professional code uses classes where they make things clearer, and plain functions everywhere else. - Inheritance is the main point of object-oriented programming.
✓ Most engineering code is clearer with composition (has-a) than with deep is-a hierarchies.
4.Discover
In the Code Lab, start from the GridMap class in the worked example. Load the small map, print neighbours((0, 0)) and neighbours((1, 1)), then add a method is_free(cell). Would a set of plain functions taking the grid as a parameter be any less clear?
Can't use the interactive? Read a description instead
The Code Lab activity can be done on paper: draw the 3 × 3 map with rows '..#', '...', '#..'. For cells (0, 0) and (1, 1), list the free neighbours up, right, down and left: (0, 0) has (0, 1) and (1, 0); (1, 1) has (0, 1), (1, 2), (2, 1) and (1, 0).
5.Checkpoint: guided practice
Check what you just discovered before going on. Hints appear after a wrong answer.
Practice 1
mm_to_inches(mm) converts a length. Class or function?
Practice 2
Using the worked example's GridMap with rows ['..#', '...', '#..'], how many neighbours does cell (2, 2) have?
6.Practice on your own
Practice, not a test. Wrong answers get a hint and another try.
Practice 3
A Robot holds two Motor objects and a RangeSensor. What is this design called?
Practice 4
Which situation most strongly suggests writing a class?
Practice 5
Why might bfs(grid, start, goal) be a function rather than a GridMap method?
7.Apply it
Sketch the design for the term project: which classes (if any) and which functions will you need? For each, write one sentence justifying the choice and list its public interface. Then implement GridMap with in_bounds, is_wall, neighbours and a from_text(text) helper, plus three tests.
8.Reflect
Concepts: Classes and objects · Robot system architecture