AlgoViz

IS-A and HAS-A

easy 40 min

IS-A says that an object is a kind of something and can stand in for it.

Watch lesson4:45

Problem

From nouns to relations: ask the right questions before drawing arrows.

The point: write the sentences first, and test each of them before it becomes an arrow.

The task

A phone shop

The shop sells three phone models. Customers choose battery and camera, some models have a pen, batteries are replaced in repair, and the shop tests phones without real batteries.

Sentences and what they tell us

SentenceTestRelation
A slab phone is a phoneFor life, and the shop sells phonesIS-A, or only a value model
A phone has a batteryReplaced in repairHAS-A, replaceable
A fast battery is a batteryCharges, has a capacityIS-A (interface)
A pen phone is a phone with a penA part againHAS-A, optional
A repair shop uses a phoneFor one job, not keptUSES-A

Three phone models differ in brand, name and parts. What are they?

BreaksOne subclass per model and option
How
SlabPhoneBigBatteryPen.
Limit
Combinations multiply, and a repaired phone has the wrong class.
Choose when
Never.
WorksOne subclass per model, parts as fields
How
SlabPhone extends Phone, with a battery field.
Limit
Good only if models differ in behaviour.
Choose when
A folding phone really opens and closes.
StrongOne class, with model as data and parts as fields
How
Phone(model, battery, camera).
Limit
A later model with special behaviour needs a new part or a subclass.
Choose when
Models differ in values and parts, as here.