TactivergeLite

Lite / Intelligent Robotic Systems / Week 2

Objects that guard their own limits

A motor is rated to 3,000 rpm. Fifteen different parts of the code set its speed. How do you make sure none of them ever asks for 3,500?

About 35 min · 3 goals · Checked by automated tests · Full interactive version

Why should I care?

An invariant is a rule that must always be true for an object: speed never exceeds the rating, stock never goes negative. If every change goes through methods that enforce the rule, you only have to get it right in one place.

Predict

Motor has max_rpm = 3000 and a method set_speed(rpm) that clamps to [0, max_rpm]. Somewhere, code writes motor.rpm = 3500 directly. What is motor.rpm afterwards?

  1. 3000, because the class clamps it
  2. 3500, because the direct assignment bypassed set_speed
  3. An error
Guess first, then reveal

3500. Plain attribute assignment skips your method entirely. Python trusts programmers, so the convention is to mark internal state with an underscore (self._rpm) and always change it through methods.

Discover

In the Code Lab, build the Motor class from the worked example. Call set_speed with 1500, 4000 and −200 and print speed each time. Then write motor._rpm = 9999 directly and print again. Add a test that would catch the bypass in a code review.

What the interactive shows (text version)

The Code Lab activity can be done on paper: a Motor rated 3000 rpm receives requests 1500, 4000 and −200 through set_speed and reports 1500, 3000 and 0. Assigning to the read-only rpm property raises AttributeError, while writing to the internal _rpm attribute bypasses the rule, which is why the convention and tests matter.

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

Understand

State changes go through methods

A Motor stores its speed in self._rpm. The method set_speed(rpm) clamps the request and is the only intended way in. Every caller gets the safety rule for free, and if the rule changes you edit one method.

Read through a property

Python's @property lets callers read motor.rpm like an attribute while it is really a method. Without a setter, motor.rpm = 3500 raises AttributeError, so the invariant can't be bypassed by accident through the public name.

Test the rule, not the code

Write tests from the invariant: after any sequence of calls, 0 ≤ rpm ≤ max_rpm. Test inside, both limits, above, below and a negative request. These tests stay valid however you rewrite the inside of the class.

Explain it another way

Intuitive

A thermostat lets you turn the dial, but the boiler has its own safety cut-out that you can't set past. Methods are the dial; the invariant is the cut-out.

Technical

Python has no truly private attributes. A single leading underscore signals 'internal'; @property creates read-only access; a @rpm.setter could validate assignments instead. Encapsulation in Python is a contract between programmers, backed by tests.

Applied

Motor controller firmware enforces current and speed limits inside the driver itself, not in every piece of code that requests motion, so a bug elsewhere can't overdrive the motor.

Worked example 1

A motor object that can never be set outside its rating.

class Motor:
    def __init__(self, name, max_rpm):
        if max_rpm <= 0:
            raise ValueError("max_rpm must be positive")
        self.name = name
        self.max_rpm = max_rpm
        self._rpm = 0

    @property
    def rpm(self):
        return self._rpm

    def set_speed(self, rpm):
        """Request a speed; it is clamped to [0, max_rpm]. Returns the speed set."""
        self._rpm = max(0, min(rpm, self.max_rpm))
        return self._rpm


m = Motor("left wheel", 3000)
print(m.set_speed(1500), m.set_speed(4000), m.set_speed(-200))   # 1500 3000 0
try:
    m.rpm = 3500
except AttributeError:
    print("rpm is read-only; use set_speed")

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.

rpm

Practice 2. Which is an invariant for an inventory Part object?
Practice 3. Motor defines rpm with @property and no setter. What does m.rpm = 3500 do?
Practice 4. part.withdraw(5) is called when quantity is 3. What should a well-designed method do?
Practice 5. Which test best checks Motor's invariant?

Apply it

Finish the inventory Part class: quantity is read through a property, withdraw(n) and restock(n) refuse invalid requests, and a test function tries at least six sequences of calls and asserts quantity ≥ 0 after each.

Reflect

Name a rule in a machine you know that should be enforced in one place rather than trusted to every user.

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

Go further

← One blueprint, many sensorsObject or function? Choosing the clearer design →