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.

PHP's tool for this is the interface: a function that depends on an interface never needs to change when a new class implements it.


The switch That Never Stops Growing

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

A switch on the shape kind

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

Prompt
Write a PHP script with a totalArea function that computes the combined area of shapes using a switch on a kind property (circle and rectangle stored in one class with width, height, radius). Print the total area of a few shapes, as the bad starting point for the Open/Closed principle.
Output: PHP script

Extend Through an Interface

The fix: each shape knows its own area. The Shape interface asks for one method, area(), and totalArea 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 totalArea is not touched. Extension without modification.

Each shape computes its own area

totalArea depends only on the Shape interface. The switch is gone — and with it, the need to ever edit this function again.

Prompt
Refactor the shapes in PHP to the Open/Closed style: a Shape interface with an area method, separate Circle and Rectangle classes that each compute their own area, and a totalArea function that sums any number of Shapes without a switch. Print the total.
Output: PHP script

Add a new shape, touch nothing

Triangle is pure new code: a class that implements area(). totalArea, Circle and Rectangle are exactly as they were — open for extension, closed for modification.

Prompt
Extend the PHP Shape interface example with a brand-new Triangle class implementing area, without modifying totalArea, Circle or Rectangle. Print the new total including the triangle to show extension without modification.
Output: PHP script
Add a new shape, touch nothing