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.

Go's tool for this is the interface: a function that depends on an interface never needs to change when a new type 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 Go program with a totalArea function that computes the combined area of shapes using a switch on a Kind field (circle and rectangle stored in one struct with width, height, radius). Print the total area of a few shapes, as the bad starting point for the Open/Closed principle.
Output: Go program and captured output

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 Go to the Open/Closed style: a Shape interface with an Area method, separate Circle and Rectangle types that each compute their own area, and a totalArea function that sums any slice of Shapes without a switch. Print the total.
Output: Go program and captured output

Add a new shape, touch nothing

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

Prompt
Extend the Go Shape interface example with a brand-new Triangle type implementing Area, without modifying totalArea, Circle or Rectangle. Print the new total including the triangle to show extension without modification.
Output: Go program and captured output
Add a new shape, touch nothing