# Open/Closed: Add, Don't Edit

When every new grading scale means editing the grade function that the whole school trusts, each new scale risks breaking the old ones; the open/closed principle says to leave working code closed to edits and open to additions, so a new scale is a new class that keeps a promise, and the grade code never changes.

Apprentice · OOP · Updated November 17, 2026

By Gregor Dzierzon

## After this lesson you can

- Add a new kind of behavior by writing new code, not by editing code that works
- Spot code that breaks open/closed, and say when editing it is still the better choice

## Key takeaways

- Code that works and is trusted should stay closed to edits: every edit risks breaking what it already does.
- It should still be open to additions: new behavior arrives as new code, such as a new class that keeps an existing promise.
- The tool that makes this possible is a promise (an interface) the code asks for, so a new kind plugs in.
- Bend it for bug fixes, and don't build places to plug in for changes nobody has asked for.

**Before this:** *Program to an Interface, Not a Class*, and *Single Responsibility: One Reason to Change*.

Northside High's grading code has been right for years, and the whole school trusts it. Now the middle school next door is joining the report-card app, and it grades on a 4-point scale: 4 for 90 and up, then 3, 2, 1 and 0. Next year the elementary school will want its own scale too. Each time, someone will open the grading code that works and change it. This lesson is about not having to.

## The symptom: the trusted code changes for every scale

Here's the grade code. It was written when there was only one scale, letters, and it answers `?` for any scale it doesn't know:

```csharp
List<(string Course, int Score)> maya = new List<(string Course, int Score)> { ("Math", 93), ("Science", 85), ("English", 71) };
Console.WriteLine(ReportLine("Maya", maya, "letter"));
Console.WriteLine(ReportLine("Maya", maya, "points"));

string Grade(int score, string scale)
{
    if (scale == "letter")
    {
        if (score >= 90) { return "A"; }
        if (score >= 80) { return "B"; }
        if (score >= 70) { return "C"; }
        if (score >= 60) { return "D"; }
        return "F";
    }
    return "?";
}

string ReportLine(string name, List<(string Course, int Score)> scores, string scale) =>
    name + ": " + string.Join(", ", scores.Select(s => s.Course + " " + Grade(s.Score, scale)));
```

```text
Maya: Math A, Science B, English C
Maya: Math ?, Science ?, English ?
```

```java
record Score(String course, int points) {}

String grade(int score, String scale) {
    if (scale.equals("letter")) {
        if (score >= 90) { return "A"; }
        if (score >= 80) { return "B"; }
        if (score >= 70) { return "C"; }
        if (score >= 60) { return "D"; }
        return "F";
    }
    return "?";
}

String reportLine(String name, List<Score> scores, String scale) {
    List<String> grades = new ArrayList<>();
    for (Score score : scores) { grades.add(score.course() + " " + grade(score.points(), scale)); }
    return name + ": " + String.join(", ", grades);
}

void main() {
    List<Score> maya = List.of(new Score("Math", 93), new Score("Science", 85), new Score("English", 71));
    IO.println(reportLine("Maya", maya, "letter"));
    IO.println(reportLine("Maya", maya, "points"));
}
```

```text
Maya: Math A, Science B, English C
Maya: Math ?, Science ?, English ?
```

```python
def grade(score, scale):
    if scale == "letter":
        if score >= 90:
            return "A"
        if score >= 80:
            return "B"
        if score >= 70:
            return "C"
        if score >= 60:
            return "D"
        return "F"
    return "?"


def report_line(name, scores, scale):
    grades = [course + " " + grade(score, scale) for course, score in scores]
    return name + ": " + ", ".join(grades)


maya = [("Math", 93), ("Science", 85), ("English", 71)]
print(report_line("Maya", maya, "letter"))
print(report_line("Maya", maya, "points"))
```

```text
Maya: Math A, Science B, English C
Maya: Math ?, Science ?, English ?
```

```javascript
function grade(score, scale) {
  if (scale === "letter") {
    if (score >= 90) { return "A"; }
    if (score >= 80) { return "B"; }
    if (score >= 70) { return "C"; }
    if (score >= 60) { return "D"; }
    return "F";
  }
  return "?";
}

function reportLine(name, scores, scale) {
  return name + ": " + scores.map(([course, score]) => course + " " + grade(score, scale)).join(", ");
}

const maya = [["Math", 93], ["Science", 85], ["English", 71]];
console.log(reportLine("Maya", maya, "letter"));
console.log(reportLine("Maya", maya, "points"));
```

```text
Maya: Math A, Science B, English C
Maya: Math ?, Science ?, English ?
```

```typescript
function grade(score: number, scale: string): string {
  if (scale === "letter") {
    if (score >= 90) { return "A"; }
    if (score >= 80) { return "B"; }
    if (score >= 70) { return "C"; }
    if (score >= 60) { return "D"; }
    return "F";
  }
  return "?";
}

function reportLine(name: string, scores: [string, number][], scale: string): string {
  return name + ": " + scores.map(([course, score]) => course + " " + grade(score, scale)).join(", ");
}

const maya: [string, number][] = [["Math", 93], ["Science", 85], ["English", 71]];
console.log(reportLine("Maya", maya, "letter"));
console.log(reportLine("Maya", maya, "points"));
```

```text
Maya: Math A, Science B, English C
Maya: Math ?, Science ?, English ?
```

The middle school's report card is a row of question marks: the grade code has never heard of points.

- **The symptom:** a new scale can only arrive by editing `Grade`, the code every report card in the school depends on, and every edit risks the scales that already work.
- **The cause:** the scales are written *inside* the grade code, as branches of one `if`. It's the growing `if` chain from *Code Smells* again, this time in code everyone trusts.

## What would you try?

**Add an `else if (scale == "points")` branch.** It works, and the letter grades are probably still right. But "probably" is the problem: the code that grades every student in the school was edited, and next year's scale edits it again.

**Copy `Grade` into `GradePoints`.** Nothing old was touched, which is good. But `ReportLine` now has to choose between the two functions, so *it* gets the growing `if` instead.

**Let each school edit its own copy of the whole app.** The copies drift apart, and a bug fixed in one stays in the others.

The second try was close: the old code wasn't edited. What's missing is a way for `ReportLine` to use any scale without knowing which one it has.

## The idea: add, don't edit

A power strip works this way. When you need another outlet, you plug a strip into the wall and plug more things into it. Nobody opens the wall and rewires the house.

![A power strip plugged into a wall outlet, with a lamp, a laptop charger and a radio plugged into it and two empty sockets waiting](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/25465f702c98410e83fc24282f663c8c.webp)

The principle is called **open/closed**: code should be **open for extension, but closed for modification**. Closed means the code that works isn't edited when something new arrives. Open means it still welcomes new behavior, added as new code. The way to get both is the idea from *Program to an Interface*: the report line asks for a promise, "something that can grade a score", and each scale is a class that keeps it.

```csharp
List<(string Course, int Score)> maya = new List<(string Course, int Score)> { ("Math", 93), ("Science", 85), ("English", 71) };
Console.WriteLine(ReportLine("Maya", maya, new LetterScale()));
Console.WriteLine(ReportLine("Maya", maya, new PointScale()));

// Closed: this never changes when a new scale arrives.
string ReportLine(string name, List<(string Course, int Score)> scores, IGradingScale scale) =>
    name + ": " + string.Join(", ", scores.Select(s => s.Course + " " + scale.Grade(s.Score)));

// Open: a new scale is a new class that keeps this promise.
interface IGradingScale
{
    string Grade(int score);
}

class LetterScale : IGradingScale
{
    public string Grade(int score)
    {
        if (score >= 90) { return "A"; }
        if (score >= 80) { return "B"; }
        if (score >= 70) { return "C"; }
        if (score >= 60) { return "D"; }
        return "F";
    }
}

class PointScale : IGradingScale
{
    public string Grade(int score)
    {
        if (score >= 90) { return "4"; }
        if (score >= 80) { return "3"; }
        if (score >= 70) { return "2"; }
        if (score >= 60) { return "1"; }
        return "0";
    }
}
```

```text
Maya: Math A, Science B, English C
Maya: Math 4, Science 3, English 2
```

```java
record Score(String course, int points) {}

// Open: a new scale is a new class that keeps this promise.
interface GradingScale {
    String grade(int score);
}

class LetterScale implements GradingScale {
    public String grade(int score) {
        if (score >= 90) { return "A"; }
        if (score >= 80) { return "B"; }
        if (score >= 70) { return "C"; }
        if (score >= 60) { return "D"; }
        return "F";
    }
}

class PointScale implements GradingScale {
    public String grade(int score) {
        if (score >= 90) { return "4"; }
        if (score >= 80) { return "3"; }
        if (score >= 70) { return "2"; }
        if (score >= 60) { return "1"; }
        return "0";
    }
}

// Closed: this never changes when a new scale arrives.
String reportLine(String name, List<Score> scores, GradingScale scale) {
    List<String> grades = new ArrayList<>();
    for (Score score : scores) { grades.add(score.course() + " " + scale.grade(score.points())); }
    return name + ": " + String.join(", ", grades);
}

void main() {
    List<Score> maya = List.of(new Score("Math", 93), new Score("Science", 85), new Score("English", 71));
    IO.println(reportLine("Maya", maya, new LetterScale()));
    IO.println(reportLine("Maya", maya, new PointScale()));
}
```

```text
Maya: Math A, Science B, English C
Maya: Math 4, Science 3, English 2
```

```python
from abc import ABC, abstractmethod


class GradingScale(ABC):
    """Open: a new scale is a new class that keeps this promise."""

    @abstractmethod
    def grade(self, score):
        ...


class LetterScale(GradingScale):
    def grade(self, score):
        if score >= 90:
            return "A"
        if score >= 80:
            return "B"
        if score >= 70:
            return "C"
        if score >= 60:
            return "D"
        return "F"


class PointScale(GradingScale):
    def grade(self, score):
        if score >= 90:
            return "4"
        if score >= 80:
            return "3"
        if score >= 70:
            return "2"
        if score >= 60:
            return "1"
        return "0"


def report_line(name, scores, scale):
    """Closed: this never changes when a new scale arrives."""
    grades = [course + " " + scale.grade(score) for course, score in scores]
    return name + ": " + ", ".join(grades)


maya = [("Math", 93), ("Science", 85), ("English", 71)]
print(report_line("Maya", maya, LetterScale()))
print(report_line("Maya", maya, PointScale()))
```

```text
Maya: Math A, Science B, English C
Maya: Math 4, Science 3, English 2
```

```javascript
// Open: a new scale is a new class with a grade(score) method.
class LetterScale {
  grade(score) {
    if (score >= 90) { return "A"; }
    if (score >= 80) { return "B"; }
    if (score >= 70) { return "C"; }
    if (score >= 60) { return "D"; }
    return "F";
  }
}

class PointScale {
  grade(score) {
    if (score >= 90) { return "4"; }
    if (score >= 80) { return "3"; }
    if (score >= 70) { return "2"; }
    if (score >= 60) { return "1"; }
    return "0";
  }
}

// Closed: this never changes when a new scale arrives.
function reportLine(name, scores, scale) {
  return name + ": " + scores.map(([course, score]) => course + " " + scale.grade(score)).join(", ");
}

const maya = [["Math", 93], ["Science", 85], ["English", 71]];
console.log(reportLine("Maya", maya, new LetterScale()));
console.log(reportLine("Maya", maya, new PointScale()));
```

```text
Maya: Math A, Science B, English C
Maya: Math 4, Science 3, English 2
```

```typescript
// Open: a new scale is a new class that keeps this promise.
interface GradingScale {
  grade(score: number): string;
}

class LetterScale implements GradingScale {
  grade(score: number): string {
    if (score >= 90) { return "A"; }
    if (score >= 80) { return "B"; }
    if (score >= 70) { return "C"; }
    if (score >= 60) { return "D"; }
    return "F";
  }
}

class PointScale implements GradingScale {
  grade(score: number): string {
    if (score >= 90) { return "4"; }
    if (score >= 80) { return "3"; }
    if (score >= 70) { return "2"; }
    if (score >= 60) { return "1"; }
    return "0";
  }
}

// Closed: this never changes when a new scale arrives.
function reportLine(name: string, scores: [string, number][], scale: GradingScale): string {
  return name + ": " + scores.map(([course, score]) => course + " " + scale.grade(score)).join(", ");
}

const maya: [string, number][] = [["Math", 93], ["Science", 85], ["English", 71]];
console.log(reportLine("Maya", maya, new LetterScale()));
console.log(reportLine("Maya", maya, new PointScale()));
```

```text
Maya: Math A, Science B, English C
Maya: Math 4, Science 3, English 2
```

The letter grades are exactly what they were, and the middle school gets its points. The 4-point scale was *added*, as a new class; `ReportLine` and `LetterScale` weren't touched, so there's nothing in them to break. Next year's elementary-school scale is one more class.

**Try it.** Add a `PassFailScale`, where 60 and up is `Pass` and anything lower is `Fail`, without editing `ReportLine` or the other scales. Maya's line should read `Maya: Math Pass, Science Pass, English Pass`.

## Where it came from

The name comes from Bertrand Meyer's 1988 book *Object-Oriented Software Construction*. Today it's read the way this lesson uses it: closed code asks for a promise, and new behavior arrives as new classes that keep it. You'll see this shape over and over in this course: a new bakery product, a new deal, a new carrier, each added without editing the code that uses them.

## When to bend it

- **Fixing a bug is an edit, and should be.** Closed doesn't mean frozen; it means a *new* kind of behavior doesn't need an edit. If the letter scale gave a B to a 90 by mistake, you would fix it in place.
- **Don't open everything ahead of time.** A promise and a class for every place that *might* change someday is extra code for a future nobody asked for. A good rule of thumb: the first time a change comes, edit; the second time the same kind of change comes, make room for the third.
- **Some code is cheap to edit.** A small script, or code with good tests that only you use, may be clearer with one more `if`.

## Check yourself

2 questions to try on the lesson page.

## So what

When a new kind of something keeps arriving, let it arrive as new code. The trusted code stays as it is, and each new kind is a class of its own that keeps the promise.

## Key terms

- [Open/Closed Principle](https://www.ask-codey.com/glossary/open-closed-principle)
- [Interface](https://www.ask-codey.com/glossary/interface-oop)
- [Polymorphism](https://www.ask-codey.com/glossary/polymorphism-oop)

## Cheat sheets

- [Open/Closed: Add, Don't Edit](https://www.ask-codey.com/cheat-sheets/dp-open-closed-cheat-sheet)

Source: https://www.ask-codey.com/lessons/dp-open-closed
