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.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:45

See it run

See what is fixed in the class and what can change in the object.

Operations

One edit, all children

The parent's battery changes. Who is hit?

Step 1 of 4

Three kinds

Smartphoneparent classbattery3000slabSlabPhonebattery3000foldFoldPhonebattery3000cheapBasicPhonebattery3000

All take the battery from the parent.

Step 1: Three kinds

class Smartphone:    battery = 3000class SlabPhone(Smartphone): passclass FoldPhone(Smartphone): passclass BasicPhone(Smartphone): passSmartphone.battery = 4000
Good for
True kinds, stable parent
Costs
Every child follows
Objects changed by one line
3

Before editing a parent, list its children. That list is the size of your change.

In the real world

The same is-a and has-a doing real jobs. Pick one and step through it.

What you are born with, and what you carry.

Step 1 of 4

Born with it

childis a Humaneyesbrownbackpackhas contentsinsidenothing

Eye colour comes from the parents.

Step 1: Born with it

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Extending for code

    critical

    The child gets every method of the parent, also the harmful ones.

    Wrong
    class Stack(list): ...
    Right
    class Stack:    def __init__(self): self._items = []
  • A class per combination

    major

    The number doubles with each option.

    Wrong
    class BigBatteryPenPhone(BigBatteryPhone)
    Right
    Phone(BigBattery(), pen=Pen())
  • A role as a subclass

    critical

    An object cannot change its class when the job ends.

    Wrong
    class Employee(Person): ...
    Right
    person.start(EmployeeRole(since=10))
  • Reaching through the part

    major

    Every caller now depends on the battery.

    Wrong
    phone.battery.charge()
    Right
    phone.charge()
  • Creating the part inside

    minor

    Nobody can choose it or fake it.

    Wrong
    self._battery = StandardBattery()
    Right
    def __init__(self, battery): self._battery = battery

Interview tips

  • Say it, then test it

    • For life?
    • All promises?
    • Used as the type?
  • Find the parts

    • Adjectives in class names
    • Optional, replaceable, for now
    • Two reasons to differ
  • Where IS-A pays

    • At the contracts
    • Among kinds of a part
    • Never for code alone
  • In the room

    • Name the change that becomes cheap
    • Draw all three arrows
    • Keep healthy hierarchies