← Back to course
Python 11-12 / Week 03 / Mission Quest
6/6
Week 03 · Guarding the State

Mission Quest

Mission Quest: Design a device
// Design a class first, then hide its data behind methods
⏱ about 30 min

Saturday: Mission Quest: Design a Device

Comet sketches a fan in her notebook: three speed buttons and a switch. "Could this be a class?" she asks. "It knows things and it does things."

Wren adds a question underneath. "What does the evidence say?" he asks. "If anyone could set the speed to 99, what would happen to the fan?"

Nova draws a box around the fan with three small windows. "How can I help?" she asks. "Decide which values stay inside, and which buttons outside users get."

Comet tears out a fresh page for you. "Find a family member, lead programmer. Pick a device at home."

Hidden values, public buttons

Design a class before writing it, with its attributes and behaviors. Encapsulation keeps the details hidden from other classes.

A real device works the same way. You press its buttons, but you cannot reach in and set the motor to any speed.

Fan (class diagram)Hidden or public?Why
_speed (0 to 3)HiddenOnly the buttons may change it
_is_onHiddenChanged by the switch
press_speed(n)PublicA button anyone may press
get_speed()PublicLets others read the speed
◇ DESIGN A DEVICE
You need paper and a pencil. Choose one device at home together, such as a lamp, a radio, a washing machine or a thermostat.
Draw a class box: the class name, three or four attributes and three behaviors.
For each attribute, decide together: hidden or public? Mark hidden ones with an underscore, like _speed.
For each hidden attribute, decide which method outside users get instead, such as a getter or a button.
Swap roles: one of you is outside code and asks for a change. The other checks it is allowed by a public method.
For a grown-up
Today's idea is encapsulation: an object keeps its own values safe and offers a few public methods instead.
Talk about it: which controls on your device could cause trouble if anyone could set them to any value? How does the design prevent it?
CHECK YOUR DESIGN
  • Read the question.
  • Tap your answer.
Which should be hidden in a Rover?
Why give a device public methods instead of open values?
When should you draw the class diagram?

Strong design work. Next week Pip starts carrying samples, and objects begin working together.

← Friday