AlgoViz

Open/closed principle

medium 55 min

Code should be open for extension and closed for modification: a new kind of thing arrives as new code, and the code that already works stays as it is.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:49

See it run

Objects at run time: what is edited, what is only added, and where the promises are checked.

Operations

The growing chain

One method knows every discount. Watch who is hit by the next one.

Step 1 of 5

Two branches

pageCartPageasks forpriceinvoicesInvoiceJobasks forpricerefundsRefundToolasks forpricecheckoutCheckoutServicebranches2last editweek 1to test again2total(cart)7000

Premium and VIP. Short, clear, and correct. Three parts of the program use it.

Step 1: Two branches

def total(self, cart):    cut = 0    if cart.tier == "premium": cut = 20    elif cart.tier == "vip": cut = 30    if cart.student: cut = 15    return cart.subtotal * (100 - cut) // 100
Good for
Two or three kinds
Costs
Every kind is an edit
Branches for n kinds
n

Look at the history of the file. The same kind of commit three times is your axis.

In the real world

The same open/closed principle doing real jobs. Pick one and step through it.

A closed case with open ports. Every device brings its own ability.

Step 1 of 7

The computer

computercase is closeddevices0screenreadycase opened0 times

The case is closed and tested. The ports are the extension points.

Step 1: The computer

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • A class where a value would do

    major

    Regular, premium and VIP differ only in a number. Three classes hide that.

    Wrong
    class PremiumCustomer(Customer):    def discount(self): return 20
    Right
    TierDiscount("premium", 20)
  • The core asks for the type

    critical

    One isinstance and the core must be edited for the next special rule.

    Wrong
    cut = rule.amount(cart)if isinstance(rule, Coupon):    cut = min(cut, left)
    Right
    cut = min(rule.amount(cart), left)   # for all rules
  • Registration order decides

    critical

    Imports run in another order on another machine, and the price changes.

    Wrong
    for rule in registry.all():      # as imported    price = rule.apply(price)
    Right
    rules = sorted(all_rules, key=lambda r: (r.stage, r.priority, r.name))
  • A contract without limits

    major

    The method exists, but a rule returns -500 or 12.5, and the error shows somewhere else.

    Wrong
    left -= rule.amount(cart)
    Right
    cut = rule.amount(cart)if cut < 0: raise ValueError(rule.name)left -= min(cut, left)
  • Sockets for a future that does not come

    minor

    Interface, factory and registry for one class: every reader takes the long way.

    Wrong
    exporter = ExporterFactory.create("pdf")   # the only one
    Right
    write_pdf(report, out)
  • Swallowing a required failure

    critical

    Isolation is right for metrics and a security hole for authentication.

    Wrong
    try: plugin.execute(request)except Exception: pass
    Right
    except Exception:    failures[plugin.name] += 1    if plugin.required: raise

Interview tips

  • Point at lines

    • Show which lines change for a new kind
    • Show which stay
    • Offer to add one live
  • Name the axis

    • Closed against new discounts
    • Not against new operations
    • Say why this axis
  • Guard the socket

    • Check limits in the core
    • Order and groups explicit
    • One contract test for all
  • Know when not

    • One example: plain code
    • Only values: a table
    • Closed set: a switch