Comet already has IDLE open. "Pip needs a class," she says. "Name, row, col, battery. I can type it in five minutes!"
Wren puts a blank sheet of graph paper over her keyboard, gently. "What does the evidence say about last week?" he asks. "Sample went smoothly because you sketched it first."
Nova projects an empty box with three sections: a name, the attributes and the behaviors. "How can I help?" she asks. "Fill the box before you type. Code is easier to change on paper."
Comet laughs and takes the pencil from behind her ear. "Fine. Lead programmer, what does a rover need to know, and what does it need to do?"
Before you write a class, it helps to design it: its attributes and its behaviors. The design can be in plain words or a diagram.
Abstraction reduces complexity by focusing on the main idea. Pip has wheels, motors and a camera, but FieldSim keeps only what the simulation needs.
| Rover (class diagram) | Entries |
|---|---|
| Attributes (what it knows) | name, row, col, heading, battery |
| Behaviors (what it does) | turn_left, turn_right, report its status |
| Starting state | row 0, col 0, heading E, battery 100 |
Comet typed a quick sketch with plain attributes anyway. Wren asks one question: what stops outside code from setting a value that makes no sense?
# rover_sketch.py
class Rover:
def __init__(self, name, row=0, col=0):
self.name = name
self.row = row
self.col = col
self.heading = "E"
self.battery = 100
pip = Rover("Pip")
print(pip.name, pip.row, pip.col, pip.heading, pip.battery)
pip.battery = -40
pip.heading = "up"
print(pip.battery, pip.heading) Pip 0 0 E 100 -40 up
No error, just a rover in a state that cannot happen on the field. That is a logic error waiting to spread. Tomorrow the crew hides the state behind methods.
| Statement | True or false? |
|---|---|
| It helps to design a class before writing it. | ? |
| A design can be in plain words or a diagram. | ? |
| rover_sketch.py stopped with an error when battery became -40. | ? |
| Abstraction keeps every detail of the real thing. | ? |
A good design makes the code easier. Tomorrow you will guard Pip's state.