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

IS-A and HAS-A

1:02Reel

Theory

Read or listen first. About 2 min.

What it is

IS-A is a relation between types: every Dog is an Animal. In code: extends, implements, : public. It promises that a dog can be used wherever an animal is expected.

HAS-A is a relation between objects: a Phone has a Battery. In code: a field. The phone asks its battery to do the work. The part can be another object tomorrow.

There is a third, weaker relation: USES-A. A method receives an object as a parameter, works with it, and keeps no field.

Why it exists

The two look alike in a sentence, and they cost very different things. An IS-A is fixed when the class is written. The subclass takes everything from the parent, including what it does not want, and every change of the parent.

A HAS-A can be chosen per object and changed while the program runs. Both sides meet only at the part's contract, so they can be tested and replaced alone.

Choosing wrong shows up late: subclasses for each combination of features, methods that make no sense on a child, and a parent nobody dares to edit.

A short history

  1. 1967

    Simula 67 introduces classes with subclasses: is-a becomes part of a programming language.

  2. 1983

    Ronald Brachman's article What IS-A Is and Isn't (IEEE Computer, October) shows that people use the same arrow for many different relations in semantic networks.

  3. 1987

    Barbara Liskov's keynote Data Abstraction and Hierarchy describes substitution, which turns is a from a phrase into a test.

  4. 1994

    The book Design Patterns by Gamma, Helm, Johnson and Vlissides gives the advice to favour object composition over class inheritance (page 20).

  5. 1997

    UML is adopted by the Object Management Group. It has one arrow for generalization and others for association, aggregation and composition.

Words to know

Generalization
The UML word for IS-A, a line with a hollow triangle at the parent.
Realization
A class implements an interface: IS-A without inherited code. Dashed line, hollow triangle.
Association
The UML word for HAS-A in general: objects of one class know objects of another.
Dependency
USES-A: a dashed arrow. No field is kept.
Substitutability
An object of the subtype keeps all promises of the general type.
Delegation
Handing a call on to a part.
Role
Something an object is for a while: employee, member, driver. Usually HAS-A.
Fragile base class
A parent whose change breaks children that looked correct.
Class explosion
One subclass per combination of features.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

Understand it

Start here

The scarecrow and its hat

Asha and Max guard a field. Some things about a scarecrow are what it is. Others are what it has.

Guards wanted
GUARDSout in all weatherfrighten birds

Frames 1 and 2 are IS-A, 3 to 5 are HAS-A, 6 is the substitution test, 7 is a role.

Three relations

Is, has and uses

IS-AHAS-AUSES-A
ExampleDog is an AnimalCar has an EnginePrinter uses a Document
BetweenTypesObjectsObjects, for one call
In codeextends, implementsA fieldA parameter
Fixed whenThe class is writtenThe object is built, or laterThe call is made
Change of the other sideReaches all childrenStops at the part's contractStops at the methods used
ReuseAll or nothingPick the parts you needPick per call
TestingThe parent's code is always insidePut a fake part inPass a fake
UMLHollow triangleLine or diamondDashed arrow
Owning a part or only knowing it is the next question: Aggregation vs composition.

IS-A goes up, HAS-A goes sideways

A tree upward with one parent, and a set of parts. You cannot choose your parents, you can choose what is in your backpack.

The smell

A phone that cannot change its battery

Python
class Smartphone:    battery = 3000    def call(self, number): return f"calling {number}"class SlabPhone(Smartphone):    def unlock(self): return "face recognised"class SlabPhoneBigBattery(SlabPhone):       # a class because of one part    battery = 5000class SlabPhoneBigBatteryPen(SlabPhoneBigBattery):   # and another    def draw(self): return "pen"p = SlabPhone()print(p.battery, p.unlock(), p.call("112"))Smartphone.battery = 4000                   # one edit of the parent ...print(p.battery, SlabPhoneBigBattery().battery)   # ... reaches old objects: 4000 5000
IS-A used for parts. Each battery needs a class, and a customer with a bigger battery needs a different phone.
Edit and run it in your browser

The bad shape: a class per combination

Smartphone# battery: int+ call(n)

1/4One parent

It looks tidy: shared fields and methods.

extends (is a)

When class names are lists of features, the features are parts.

The good shape: an interface outside, parts inside

«interface»Callable+ call(n)Phone- battery: Battery- camera: Camera+ call(n)+ charge()

1/4What it is

Others use the phone through a small contract. This is the IS-A that pays.

implementshas (lives on)

Good designs use both relations. The question is where.

The test

Four questions before you write extends

  1. 1

    Is the sentence true in both directions of time?

    Every X is a Y, always, from creation to the end. A person is not an employee from birth to death.

  2. 2

    Does it keep all promises?

    Read the parent's methods one by one. Is each meaningful on the child, with the same rules?

  3. 3

    Does somebody use it through the parent type?

    If nobody ever writes the parent as a parameter type, you only wanted its code.

  4. 4

    Is there one reason to differ?

    Two independent reasons (battery, pen) mean two parts.

IS-A or HAS-A?

Practice with sentences

PairVerdictWhy
Dog, AnimalIS-AFor life, and used as an animal
Car, EngineHAS-AA car is no engine
Employee, AddressHAS-AIt can move house
Employee, PersonUsually HAS-A (a role)Jobs begin and end, and one person can have two
Square, RectangleDependsYes if both are immutable. No if a rectangle promises to change width alone. See LSP
Stack, ListHAS-AA list promises insertion in the middle
Car, VehicleIS-A, if someone drives vehiclesNot better or worse than car has an engine: both can be true
Manager, List of EmployeeHAS-AIt manages several and is not a list
SavingsAccount, AccountIS-A, if withdraw keeps its rulesRead the promises first

Trade

What each relation costs

  • Tight coupling

    A child uses the parent's inner steps. A changed step in the parent changes every child.

  • Fragile parent

    A new parent method may clash with a child's method of the same name.

  • No change at run time

    An object cannot change its class. A field can point to another part.

  • Indirection

    HAS-A needs forwarding methods and wiring. Ten parts make a class hard to set up.

  • Identity

    A part does not know its wrapper. Calls that the part makes to itself do not pass the wrapper.

  • No common type

    HAS-A alone does not let you pass one as the other. Add an interface.

The long discussion, with the fragile base class shown in code, is on Inheritance vs composition. How parts are put together well is on Object composition.

IS-A when

  • A true kind for its whole life
  • You need to pass it as the general type
  • All promises hold (LSP)
  • The parent is abstract or made for extension

HAS-A when

  • It may change or be missing
  • Several features combine
  • You only want some of the code
  • Tests need a fake in its place

One call in a design with parts

The customer talks to the phone only. Which battery answers is the phone's business.

Summary

The whole topic in one minute.

Say the sentence, then test it. IS-A needs four yeses: a true kind, for its whole life, with every inherited promise kept, and someone who uses it through the parent type.

Otherwise HAS-A: a field with a small contract. Parts can be swapped, shared, faked and combined.

Interfaces give the useful half of IS-A, standing in, without inheriting code. Most good designs are an interface on the outside and parts on the inside.

  • IS-A: a kind, for life, keeping all promises, used through the general type.
  • HAS-A: a field. USES-A: a parameter.
  • Implementing an interface is IS-A without inherited code.
  • Feature lists in class names mean parts.
  • Roles that begin and end are HAS-A.
  • Favour HAS-A when both would work. Keep IS-A for true kinds.

Sources