OOP anti-patterns
medium 50 minAn anti-pattern is a common answer that looks helpful and costs more than it gives: the god object, spaghetti code, copy and paste, the golden hammer, cargo cult and early optimization.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
How they grow, what they cost, and the small steps out.
Operations
The god object grows
Each step is reasonable. Look at the last column.
Step 1 of 4
Three methods
One place for everything. This is fine.
Step 1: Three methods
class AppManager: def create_user(self, name, email): ... def send_email(self, to, text): ... def process_payment(self, email, cents): ... def generate_report(self): ... # validate_input, log_event, cache_data, # format_output, handle_error, and 41 more- Good for
- Seeing the first signs
- Costs
- Every team in one file
Count groups, not lines.
In the real world
The same oop anti-patterns doing real jobs. Pick one and step through it.
The same five parts with other arrows.
Step 1 of 3
Tangled
Everything calls everything. A change in the store reaches the page by three ways.
Step 1: Tangled
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Extract in the wrong order
majorThe new class needs the old one, which holds it: a ring.
Wrongclass UserService: def __init__(self, manager): ...Rightclass UserService: def __init__(self, outbox): ...Split by size
majorParts that must agree are now in two classes.
Wrongclass SpotFinder: ...class SpotTaker: ...Rightclass Lot: def take_spot(self): ... # find and take in one stepA pattern without a reason
minorReaders take the long way to one line.
WrongReportFactoryProvider().get().create()RightReport()Join by looks
majorTwo rules now share a body and need flags.
Wrongdef price(x, is_shop=False, is_bank=False): ...Rightdef shop_price(x): ...def bank_price(x): ...Compare by running the effect twice
criticalThe customer pays twice.
Wrongold.pay(user, 500); new.pay(user, 500)Rightassert new.total(500) == old.total(500)
Interview tips
Name it early
- This could become a god object
- Here is the first cut
- Not now, because...
Split by change
- Who asks for the change?
- Which fields together?
- What must be atomic?
Stay plain
- No factory for one class
- No cache without a target
- Copies are allowed
Repair safely
- Record behaviour
- Front and one group
- Delete the old path