DRY
easy 40 minDon'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 see | Say | Because |
|---|---|---|
| The same check in two methods | This rule gets one home | It will change together |
| The same number twice | Are these the same fact? | Equal values may be two facts |
| Two classes that look alike | I keep both until a third | The common part is not clear yet |
| A helper with a boolean parameter | Who passes true? Maybe two functions | Flags hide two facts |
| A total stored beside its lines | I compute it, or I say who is in charge | A 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
Interviewer
You wrote the overlap check in both
bookandmove.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.Interviewer
The fee code in both looks similar too.
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.