AlgoViz

OOP anti-patterns

medium 50 min

An 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

0:00 / 4:28

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

web teamcallernight teamcallermobile teamcallermanagerAppManagermethods3fields2test needsnothing

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

pagepresentationordersbusiness logicstoredata accessmaildata accessreportpresentation

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

    major

    The new class needs the old one, which holds it: a ring.

    Wrong
    class UserService:    def __init__(self, manager): ...
    Right
    class UserService:    def __init__(self, outbox): ...
  • Split by size

    major

    Parts that must agree are now in two classes.

    Wrong
    class SpotFinder: ...class SpotTaker: ...
    Right
    class Lot:    def take_spot(self): ...   # find and take in one step
  • A pattern without a reason

    minor

    Readers take the long way to one line.

    Wrong
    ReportFactoryProvider().get().create()
    Right
    Report()
  • Join by looks

    major

    Two rules now share a body and need flags.

    Wrong
    def price(x, is_shop=False, is_bank=False): ...
    Right
    def shop_price(x): ...def bank_price(x): ...
  • Compare by running the effect twice

    critical

    The customer pays twice.

    Wrong
    old.pay(user, 500); new.pay(user, 500)
    Right
    assert 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