TactivergeLite

Lite / Intelligent Robotic Systems / Week 1

Functions that keep their promises

In 1999 a Mars orbiter was lost because one team's software worked in pound-force seconds and another's expected newton-seconds. What one line of documentation could have helped?

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

Why should I care?

A function's contract is its promise: give me these inputs, in these units, and I will return this. Teams build on each other's contracts every day. Writing them down, and checking them, turns silent wrong answers into loud, early errors.

Predict

battery_runtime_h(capacity_mah, current_ma) returns capacity / current. Someone calls it with current_ma = 0. What should a well-designed version do?

  1. Return 0
  2. Return a huge number
  3. Raise a ValueError explaining that current must be positive
  4. Print a warning and carry on
Guess first, then reveal

Raise a clear error. A zero current breaks the contract, and any number it returned would be a lie that flows into later calculations. A ValueError with a message points straight at the faulty caller.

Discover

In the Code Lab, write battery_runtime_h with a docstring and a check that both inputs are positive. Call it with good values, then with current_ma = 0 and capacity_mah = -500. Read each error message: does it tell the caller what to fix?

What the interactive shows (text version)

The Code Lab activity can be done on paper: write the function's docstring with inputs, units, ranges and return value, then list what it should do for capacity 2200 and current 550 (return 4.0), current 0 (raise ValueError) and capacity −500 (raise ValueError).

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

Understand

A docstring is the contract

State what each parameter means, its units and allowed range, what is returned (with units), and what happens on bad input. Someone should be able to use the function correctly from the docstring alone, without reading the body.

One job, returned not printed

A function that reads a file, converts units, averages and prints is four functions tangled together. Split it so each does one thing and returns its result. Returned values can be tested, reused and fed into the next step; printed text can only be read by a person.

Fail loudly at the boundary

Check preconditions at the top of the function and raise ValueError("...") with a message that names the bad value. An early, specific error is far cheaper than a wrong number discovered three modules later.

Explain it another way

Intuitive

A vending machine has a contract printed on it: insert coins, press a code, get a snack. It rejects foreign coins straight away instead of keeping them and giving you nothing. Good functions behave the same way.

Technical

Preconditions are what must be true of the inputs; postconditions are what the function guarantees about its output. Python's convention is to raise ValueError for a value of the right type but wrong range and TypeError for the wrong type. Type hints such as def f(x: float) -> float document types but are not enforced at run time.

Applied

Flight software standards require every interface to state units and ranges, because many costly failures have come from two correct pieces of code that disagreed about what a number meant.

Worked example 1

Write a contract-checked runtime function for a robot battery.

def battery_runtime_h(capacity_mah, current_ma):
    """Estimate runtime in hours.

    capacity_mah: usable capacity in milliamp-hours, > 0
    current_ma:   average current draw in milliamps, > 0
    Returns the runtime in hours. Raises ValueError for non-positive inputs.
    """
    if capacity_mah <= 0:
        raise ValueError(f"capacity_mah must be positive, got {capacity_mah}")
    if current_ma <= 0:
        raise ValueError(f"current_ma must be positive, got {current_ma}")
    return capacity_mah / current_ma


print(battery_runtime_h(2200, 550))   # 4.0
try:
    battery_runtime_h(2200, 0)
except ValueError as err:
    print("Rejected:", err)

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. Docstring: 'Returns the distance.' What is the most important thing missing for an engineer using it?

h

Practice 3. Which function design is best for a sensor-log tool?
Practice 4. wheel_rpm(speed_m_s, diameter_m) is called with diameter_m = -0.1. Which response best keeps the contract?
Practice 5. A function prints the average current instead of returning it. What can't you do?

Apply it

Write wheel_rpm(speed_m_s, diameter_m) for a rover: a docstring with units and ranges, checks that raise ValueError for bad inputs, and a returned value. Test it on 0.5 m/s with a 0.12 m wheel (about 79.6 rpm) and on two bad inputs.

Reflect

Think of a number you have computed before without writing its unit. How could it have been misread?

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

Go further

← One script is not a systemTests that catch you before the robot does →