TactivergeLite

Lite / Intelligent Robotic Systems / Week 2

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 · Full interactive version

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.

Predict

Which of these is the best candidate for a class?

  1. deg_to_rad(deg): one formula
  2. A grid map that stores cells, knows which are walls and lists a cell's neighbours
  3. Adding two numbers
Guess first, then reveal

The grid map: it has data (the cells) and several operations that must agree about that data (is_wall, neighbours, cost). A single formula has no state to protect, so a function is clearer.

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?

What the interactive shows (text version)

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).

You can also open the interactive on the full site when you have a faster connection.

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

Intuitive

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.

Technical

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.

Applied

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

Practice

Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.

Practice 1. mm_to_inches(mm) converts a length. Class or function?

cells

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?

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.

Reflect

Describe one piece of code where you'd now choose a function over a class (or the other way round), and why.

Write your answer on paper or in your own notes. Lite never stores what you write.

← Objects that guard their own limitsSlice, filter, transform: lists at speed →