AlgoViz

DRY

easy 40 min

Don't repeat yourself: every piece of knowledge has one home, and everything else asks that home.

Watch lesson4:18

When it comes up

The moments this idea belongs in a design interview, and the moments it does not.

Signals

When to bring it up

You seeSayBecause
The same check in two methodsThis rule gets one homeIt will change together
The same number twiceAre these the same fact?Equal values may be two facts
Two classes that look alikeI keep both until a thirdThe common part is not clear yet
A helper with a boolean parameterWho passes true? Maybe two functionsFlags hide two facts
A total stored beside its linesI compute it, or I say who is in chargeA stored copy can drift

Car and Truck have the same park() body in your parking lot. What do you do?

BreaksLeave both and a third for Bus
How
Copy the method again.
Limit
A change of the parking rule needs three edits.
Choose when
Never, the rule is clearly one.
WorksPut it into a base class Vehicle
How
Vehicle has park(), the subclasses inherit it.
Limit
Parking is the lot's knowledge and not the vehicle's.
Choose when
If vehicles really decide how they park.
StrongPut it where the knowledge is
How
ParkingLot.park(vehicle) is written once, and a vehicle only tells its size.
Limit
Needs a clear size value.
Choose when
The rule depends on the lot.

A short exchange

  1. Interviewer

    You wrote the overlap check in both book and move.

  2. You

    Yes, and it is one rule: two bookings of a room may not overlap. I will extract overlaps(a, b) and test its edges once.

  3. Interviewer

    The fee code in both looks similar too.

  4. You

    It does today. A move may become free next month, as you said. Two reasons, so I keep two methods and share only the rounding of money.