Designbench

Lesson 7.1 · 25 min

Object-oriented design

Add electric cars to a switch-based parking lot and watch 3 files change, then add them to a polymorphic one and change nothing; flip through SOLID before/afters in Java and watch 32 notifier classes shrink to 8.

The idea in plain words

Object-oriented design is deciding which “things” your program is made of, what each one is responsible for, and how they talk to each other. A good design lets you add the next feature by adding a class, not by editing ten existing ones.

The problem it solves

Code that works today often becomes painful when the next requirement arrives. Low-level design interviews test whether you can structure a feature so changes land in one place.

How it works

  1. Clarify what the system must do; ask about the edge cases.
  2. Find the things (nouns) and give each one a class with one clear job.
  3. Find the actions (verbs) and make them methods on the class that owns that data.
  4. Where behaviour varies, put it behind an interface so new variants are new classes.
  5. Check the design by adding a new requirement and counting what you had to change.

Example

A parking lot charges cars, motorbikes and trucks differently. With an if/else on vehicle type, adding electric cars means editing every if/else. With a PricingPolicy interface, it means adding one ElectricCarPricing class.

Key terms

Class / object
A class is a blueprint (ParkingSpot); an object is one instance of it (spot 42).
Interface
A promise of what methods a class offers, without saying how they work.
Encapsulation
Keeping an object’s data private and changing it only through its methods.
Polymorphism
Different classes answering the same method call in their own way.
Composition
Building objects out of other objects (“has a”) instead of inheriting (“is a”).
SOLID
Five rules for designs that are easy to change, starting with “one reason to change per class”.

In this lesson you'll learn

Sections

  1. Theory: the interview flow
  2. Theory: polymorphism pays
  3. Theory: SOLID
  4. Theory: composition
  5. Theory: parking lot
  6. Design: spot the smell
  7. Check yourself

Cheat sheet

Flowclarify → nouns → verbs → relations → interfaces
New typenew class, not a new case
SOLIDS O L I D, one before/after each
Reusecomposition over inheritance
Testsinject Clock and policies

The interactive simulations and the quiz load with JavaScript.