Skip to main content

Open for Extension, Closed for Modification

The Open/Closed Principle says: code should be open for extension — new behavior can be added — but closed for modification — existing, working, tested code is not edited for it.

Every edit to working code is a chance to break it. When adding a feature means only adding new code, the old code stays proven.

Python's tool for this is the protocol: a class built on typing.Protocol that lists the methods a type must have. Any class with matching methods satisfies the protocol automatically — nothing is declared — so a function that depends on a protocol never needs to change when a new class plugs in.


The match That Never Stops Growing

This area calculator uses a match on the shape kind. It works — until the next shape arrives. Triangle? Edit the match. Pentagon? Edit it again. The function is never finished, and every edit risks the shapes that already worked.

A match on the shape kind

total_area must know every kind of shape. Adding one means modifying this tested function — the exact thing the principle warns against.

Prompt
Write a Python program with a total_area function that computes the combined area of shapes using a match on a kind field (circle and rectangle stored in one dataclass with width, height, radius). Print the total area of a few shapes, as the bad starting point for the Open/Closed principle.
Output: complete Python program

Extend Through a Protocol

The fix: each shape knows its own area. The Shape protocol asks for one method, area(), and total_area just adds up whatever it receives — it no longer cares what the shapes are.

Now watch the principle at work: a brand-new Triangle plugs in, and total_area is not touched. Extension without modification.

Each shape computes its own area

total_area depends only on the Shape protocol. The match is gone — and with it, the need to ever edit this function again.

Prompt
Refactor the shapes in Python to the Open/Closed style: a Shape protocol with an area method, separate Circle and Rectangle dataclasses that each compute their own area, and a total_area function that sums any list of shapes without a match. Print the total.
Output: complete Python program

Add a new shape, touch nothing

Triangle is pure new code: a dataclass and its area() method. total_area, Circle and Rectangle are exactly as they were — open for extension, closed for modification.

Prompt
Extend the Python Shape protocol example with a brand-new Triangle dataclass implementing area, without modifying total_area, Circle or Rectangle. Print the new total including the triangle to show extension without modification.
Output: complete Python program
Add a new shape, touch nothing