# When Repetition Becomes a Pattern: The Rule of Three

When the same solution turns up for the third time, each copy a little different, it's time to pull out its shared shape and give it a name; once is code, twice is a coincidence, and three times is a pattern worth naming, which is how every pattern in this course began.

Journeyman · Software Development · OOP · Updated November 17, 2026

By Gregor Dzierzon

## After this lesson you can

- Use the rule of three to decide when a repeated solution is worth naming and sharing
- Find the shared shape in three near-identical pieces of code, and the one part that differs
- Spot the smells that point to a pattern of your own: the same steps copied three times, each copy a little different

## Key takeaways

- Once is code, twice is a coincidence, three times is a pattern worth naming: the rule of three.
- Two copies don't yet show which parts really vary; three usually do, so pulling out a shape after two often guesses wrong.
- A shared shape keeps the steps that are the same, and takes the one part that differs as a parameter, often a function.
- Every pattern in this course was found this way: teams solved the same problem three times, and someone wrote it down.

**Before this:** *Functions as Values* (handing a function to another function), and *Template Method: Same Routine, Your Own Step*.

Summit Gym's booking system loads three spreadsheets: the front desk's list of members, the schedule team's list of instructors, and the timetable team's list of class times. Each team wrote its own importer, the second by copying the first and the third by copying the second. Now the equipment team wants to load their spreadsheet too, and the quickest way is another copy. Should you copy it a fourth time, or do something else? Every developer meets this question, usually on a Friday afternoon, and it has an answer with a name: the *rule of three*.

## The symptom: the same steps, three times

```csharp
string membersFile = "name,plan\nMaya, basic\nSam,unlimited\n\nLeo,basic";
string instructorsFile = "name,class\nPriya,yoga\nOmar, spin";
string classTimesFile = "class,time\nyoga,07:00\n\nspin,12:00\nHIIT,18:00";

Console.WriteLine("Members: " + string.Join(", ", ImportMembers(membersFile)));
Console.WriteLine("Instructors: " + string.Join(", ", ImportInstructors(instructorsFile)));
Console.WriteLine("Class times: " + string.Join(", ", ImportClassTimes(classTimesFile)));

// The front desk's importer, written first.
List<string> ImportMembers(string text)
{
    List<string> members = new List<string>();
    foreach (string line in text.Trim().Split('\n').Skip(1))
    {
        if (line.Trim() == "") { continue; }
        string[] parts = line.Split(',').Select(part => part.Trim()).ToArray();
        members.Add($"{parts[0]} ({parts[1]})");
    }
    return members;
}

// The schedule team's copy, a few weeks later.
List<string> ImportInstructors(string text)
{
    List<string> instructors = new List<string>();
    string[] lines = text.Trim().Split('\n');
    foreach (string line in lines.Skip(1))
    {
        if (string.IsNullOrWhiteSpace(line)) { continue; }
        string[] values = line.Split(',');
        instructors.Add(values[0].Trim() + " teaches " + values[1].Trim());
    }
    return instructors;
}

// The timetable team's copy of the copy.
List<string> ImportClassTimes(string text)
{
    List<string> times = new List<string>();
    string[] lines = text.Trim().Split('\n');
    for (int i = 1; i < lines.Length; i++)
    {
        if (lines[i].Trim().Length == 0) { continue; }
        string[] cells = lines[i].Split(',');
        times.Add($"{cells[0].Trim()} at {cells[1].Trim()}");
    }
    return times;
}
```

```text
Members: Maya (basic), Sam (unlimited), Leo (basic)
Instructors: Priya teaches yoga, Omar teaches spin
Class times: yoga at 07:00, spin at 12:00, HIIT at 18:00
```

```java
// The front desk's importer, written first.
List<String> importMembers(String text) {
    List<String> members = new ArrayList<>();
    for (String line : text.strip().lines().skip(1).toList()) {
        if (line.strip().isEmpty()) { continue; }
        String[] parts = line.split(",");
        members.add(parts[0].strip() + " (" + parts[1].strip() + ")");
    }
    return members;
}

// The schedule team's copy, a few weeks later.
List<String> importInstructors(String text) {
    List<String> instructors = new ArrayList<>();
    List<String> lines = text.strip().lines().toList();
    for (String line : lines.subList(1, lines.size())) {
        if (line.isBlank()) { continue; }
        String[] values = line.split(",");
        instructors.add(values[0].strip() + " teaches " + values[1].strip());
    }
    return instructors;
}

// The timetable team's copy of the copy.
List<String> importClassTimes(String text) {
    List<String> times = new ArrayList<>();
    String[] lines = text.strip().split("\n");
    for (int i = 1; i < lines.length; i++) {
        if (lines[i].strip().length() == 0) { continue; }
        String[] cells = lines[i].split(",");
        times.add(cells[0].strip() + " at " + cells[1].strip());
    }
    return times;
}

void main() {
    String membersFile = "name,plan\nMaya, basic\nSam,unlimited\n\nLeo,basic";
    String instructorsFile = "name,class\nPriya,yoga\nOmar, spin";
    String classTimesFile = "class,time\nyoga,07:00\n\nspin,12:00\nHIIT,18:00";

    IO.println("Members: " + String.join(", ", importMembers(membersFile)));
    IO.println("Instructors: " + String.join(", ", importInstructors(instructorsFile)));
    IO.println("Class times: " + String.join(", ", importClassTimes(classTimesFile)));
}
```

```text
Members: Maya (basic), Sam (unlimited), Leo (basic)
Instructors: Priya teaches yoga, Omar teaches spin
Class times: yoga at 07:00, spin at 12:00, HIIT at 18:00
```

```python
def import_members(text):
    """The front desk's importer, written first."""
    members = []
    for line in text.strip().split("\n")[1:]:
        if line.strip() == "":
            continue
        name, plan = [part.strip() for part in line.split(",")]
        members.append(f"{name} ({plan})")
    return members


def import_instructors(text):
    """The schedule team's copy, a few weeks later."""
    instructors = []
    lines = text.strip().split("\n")
    for line in lines[1:]:
        if not line.strip():
            continue
        values = line.split(",")
        instructors.append(values[0].strip() + " teaches " + values[1].strip())
    return instructors


def import_class_times(text):
    """The timetable team's copy of the copy."""
    times = []
    lines = text.strip().split("\n")
    for i in range(1, len(lines)):
        if len(lines[i].strip()) == 0:
            continue
        gym_class, time = lines[i].split(",")
        times.append(f"{gym_class.strip()} at {time.strip()}")
    return times


members_file = "name,plan\nMaya, basic\nSam,unlimited\n\nLeo,basic"
instructors_file = "name,class\nPriya,yoga\nOmar, spin"
class_times_file = "class,time\nyoga,07:00\n\nspin,12:00\nHIIT,18:00"

print("Members: " + ", ".join(import_members(members_file)))
print("Instructors: " + ", ".join(import_instructors(instructors_file)))
print("Class times: " + ", ".join(import_class_times(class_times_file)))
```

```text
Members: Maya (basic), Sam (unlimited), Leo (basic)
Instructors: Priya teaches yoga, Omar teaches spin
Class times: yoga at 07:00, spin at 12:00, HIIT at 18:00
```

```javascript
// The front desk's importer, written first.
function importMembers(text) {
  const members = [];
  for (const line of text.trim().split("\n").slice(1)) {
    if (line.trim() === "") { continue; }
    const [name, plan] = line.split(",").map((part) => part.trim());
    members.push(`${name} (${plan})`);
  }
  return members;
}

// The schedule team's copy, a few weeks later.
function importInstructors(text) {
  const instructors = [];
  const lines = text.trim().split("\n");
  for (const line of lines.slice(1)) {
    if (!line.trim()) { continue; }
    const values = line.split(",");
    instructors.push(values[0].trim() + " teaches " + values[1].trim());
  }
  return instructors;
}

// The timetable team's copy of the copy.
function importClassTimes(text) {
  const times = [];
  const lines = text.trim().split("\n");
  for (let i = 1; i < lines.length; i++) {
    if (lines[i].trim().length === 0) { continue; }
    const cells = lines[i].split(",");
    times.push(`${cells[0].trim()} at ${cells[1].trim()}`);
  }
  return times;
}

const membersFile = "name,plan\nMaya, basic\nSam,unlimited\n\nLeo,basic";
const instructorsFile = "name,class\nPriya,yoga\nOmar, spin";
const classTimesFile = "class,time\nyoga,07:00\n\nspin,12:00\nHIIT,18:00";

console.log("Members: " + importMembers(membersFile).join(", "));
console.log("Instructors: " + importInstructors(instructorsFile).join(", "));
console.log("Class times: " + importClassTimes(classTimesFile).join(", "));
```

```text
Members: Maya (basic), Sam (unlimited), Leo (basic)
Instructors: Priya teaches yoga, Omar teaches spin
Class times: yoga at 07:00, spin at 12:00, HIIT at 18:00
```

```typescript
// The front desk's importer, written first.
function importMembers(text: string): string[] {
  const members: string[] = [];
  for (const line of text.trim().split("\n").slice(1)) {
    if (line.trim() === "") { continue; }
    const [name, plan] = line.split(",").map((part) => part.trim());
    members.push(`${name} (${plan})`);
  }
  return members;
}

// The schedule team's copy, a few weeks later.
function importInstructors(text: string): string[] {
  const instructors: string[] = [];
  const lines = text.trim().split("\n");
  for (const line of lines.slice(1)) {
    if (!line.trim()) { continue; }
    const values = line.split(",");
    instructors.push(values[0].trim() + " teaches " + values[1].trim());
  }
  return instructors;
}

// The timetable team's copy of the copy.
function importClassTimes(text: string): string[] {
  const times: string[] = [];
  const lines = text.trim().split("\n");
  for (let i = 1; i < lines.length; i++) {
    if (lines[i].trim().length === 0) { continue; }
    const cells = lines[i].split(",");
    times.push(`${cells[0].trim()} at ${cells[1].trim()}`);
  }
  return times;
}

const membersFile = "name,plan\nMaya, basic\nSam,unlimited\n\nLeo,basic";
const instructorsFile = "name,class\nPriya,yoga\nOmar, spin";
const classTimesFile = "class,time\nyoga,07:00\n\nspin,12:00\nHIIT,18:00";

console.log("Members: " + importMembers(membersFile).join(", "));
console.log("Instructors: " + importInstructors(instructorsFile).join(", "));
console.log("Class times: " + importClassTimes(classTimesFile).join(", "));
```

```text
Members: Maya (basic), Sam (unlimited), Leo (basic)
Instructors: Priya teaches yoga, Omar teaches spin
Class times: yoga at 07:00, spin at 12:00, HIIT at 18:00
```

Read the three side by side and they do the same four things: skip the header line, skip blank lines, split each line at its commas, and trim the spaces off each value. Only the names (`parts`, `values`, `cells`), the loop style and the last line differ. And the last line is the one real difference: what each row becomes.

Each copy works. The cost shows up later. A fix, say for a line that ends with a stray comma, has to be found and made three times, and a fourth copy makes it four. The copies have already started to drift: give them a row with a missing value, and they fail in different ways.

Read it as a doctor would:

- **The symptom:** the same steps copied into three places, each copy a little different.
- **The cause:** a solution the team keeps needing has no home and no name, so each team writes it again.
- **The cure:** pull out the shared shape and name it. The harder question is *when*.

## When is it time? The rule of three

**Once is code, twice is a coincidence, three times is a pattern worth naming.**

After the first importer, there's nothing to share. After the second, you can see two copies, but not yet which parts will really vary: maybe class times will need a check that the time is real, maybe instructors will need a second class column. Pull out a shared shape now and you're guessing, and a wrong shared shape is harder to undo than two copies, because everything that uses it has to be untangled. After the third, the shape is clear: the same four steps every time, and one part that differs, what a row becomes.

The rule is usually credited to Don Roberts, through Martin Fowler's book *Refactoring* (1999): the first time, do it; the second time, notice the copy and do it anyway; the third time, pull out the shared part.

## What would you try?

**Copy it a fourth time.** Fast today. Four places to fix tomorrow, and the equipment copy will drift like the others.

**One big importer with a flag:** `importFile(text, "members")`, with an `if` for each kind of spreadsheet inside. One place, but every new spreadsheet edits it: it's Pass 1's growing `if` chain again.

**A base class every importer inherits from,** with a method each one overrides for its rows. It works (it's Template Method), and it's more machinery than needed when only one small step differs.

What we want: the four shared steps written once, and the one part that differs handed in from outside.

## The everyday version: three footprints

Picture a lawn between a parking lot and a door. The first person who cuts across leaves no mark. After a few more, there's a faint trail. After enough of them, there's a path, and the groundskeeper stops fighting it and paves it. Nobody designed the path; people kept walking it, and someone made it official.

![A lawn with three sets of footprints crossing it along the same line, from a parking lot to a building's side door; the oldest footprints are faint, the newest are clear, and a groundskeeper at the far end is laying the first paving stones along the line they made](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/e5feae67fe9546a49d7a935dc706a2bd.webp)

## The fix: pull out the shared shape

**The fix in one sentence:** write the steps that were the same once, in one function, and hand that function the one part that differs.

```csharp
string membersFile = "name,plan\nMaya, basic\nSam,unlimited\n\nLeo,basic";
string instructorsFile = "name,class\nPriya,yoga\nOmar, spin";
string classTimesFile = "class,time\nyoga,07:00\n\nspin,12:00\nHIIT,18:00";

Console.WriteLine("Members: " + string.Join(", ", ImportRows(membersFile, row => $"{row[0]} ({row[1]})")));
Console.WriteLine("Instructors: " + string.Join(", ", ImportRows(instructorsFile, row => $"{row[0]} teaches {row[1]}")));
Console.WriteLine("Class times: " + string.Join(", ", ImportRows(classTimesFile, row => $"{row[0]} at {row[1]}")));

// The shape all three copies shared: skip the header and blank lines, split each line and trim its values.
// The one part that differs, turning a row into something, is handed in.
List<T> ImportRows<T>(string text, Func<string[], T> makeRow)
{
    List<T> rows = new List<T>();
    foreach (string line in text.Trim().Split('\n').Skip(1))
    {
        if (line.Trim() == "") { continue; }
        rows.Add(makeRow(line.Split(',').Select(value => value.Trim()).ToArray()));
    }
    return rows;
}
```

```text
Members: Maya (basic), Sam (unlimited), Leo (basic)
Instructors: Priya teaches yoga, Omar teaches spin
Class times: yoga at 07:00, spin at 12:00, HIIT at 18:00
```

```java
// The shape all three copies shared: skip the header and blank lines, split each line and trim its values.
// The one part that differs, turning a row into something, is handed in.
<T> List<T> importRows(String text, Function<String[], T> makeRow) {
    List<T> rows = new ArrayList<>();
    for (String line : text.strip().lines().skip(1).toList()) {
        if (line.isBlank()) { continue; }
        String[] values = Arrays.stream(line.split(",")).map(String::strip).toArray(String[]::new);
        rows.add(makeRow.apply(values));
    }
    return rows;
}

void main() {
    String membersFile = "name,plan\nMaya, basic\nSam,unlimited\n\nLeo,basic";
    String instructorsFile = "name,class\nPriya,yoga\nOmar, spin";
    String classTimesFile = "class,time\nyoga,07:00\n\nspin,12:00\nHIIT,18:00";

    IO.println("Members: " + String.join(", ", importRows(membersFile, row -> row[0] + " (" + row[1] + ")")));
    IO.println("Instructors: " + String.join(", ", importRows(instructorsFile, row -> row[0] + " teaches " + row[1])));
    IO.println("Class times: " + String.join(", ", importRows(classTimesFile, row -> row[0] + " at " + row[1])));
}
```

```text
Members: Maya (basic), Sam (unlimited), Leo (basic)
Instructors: Priya teaches yoga, Omar teaches spin
Class times: yoga at 07:00, spin at 12:00, HIIT at 18:00
```

```python
def import_rows(text, make_row):
    """The shape all three copies shared: skip the header and blank lines, split each line and trim its values.
    The one part that differs, turning a row into something, is handed in."""
    rows = []
    for line in text.strip().split("\n")[1:]:
        if line.strip() == "":
            continue
        rows.append(make_row([value.strip() for value in line.split(",")]))
    return rows


members_file = "name,plan\nMaya, basic\nSam,unlimited\n\nLeo,basic"
instructors_file = "name,class\nPriya,yoga\nOmar, spin"
class_times_file = "class,time\nyoga,07:00\n\nspin,12:00\nHIIT,18:00"

print("Members: " + ", ".join(import_rows(members_file, lambda row: f"{row[0]} ({row[1]})")))
print("Instructors: " + ", ".join(import_rows(instructors_file, lambda row: f"{row[0]} teaches {row[1]}")))
print("Class times: " + ", ".join(import_rows(class_times_file, lambda row: f"{row[0]} at {row[1]}")))
```

```text
Members: Maya (basic), Sam (unlimited), Leo (basic)
Instructors: Priya teaches yoga, Omar teaches spin
Class times: yoga at 07:00, spin at 12:00, HIIT at 18:00
```

```javascript
// The shape all three copies shared: skip the header and blank lines, split each line and trim its values.
// The one part that differs, turning a row into something, is handed in.
function importRows(text, makeRow) {
  const rows = [];
  for (const line of text.trim().split("\n").slice(1)) {
    if (line.trim() === "") { continue; }
    rows.push(makeRow(line.split(",").map((value) => value.trim())));
  }
  return rows;
}

const membersFile = "name,plan\nMaya, basic\nSam,unlimited\n\nLeo,basic";
const instructorsFile = "name,class\nPriya,yoga\nOmar, spin";
const classTimesFile = "class,time\nyoga,07:00\n\nspin,12:00\nHIIT,18:00";

console.log("Members: " + importRows(membersFile, (row) => `${row[0]} (${row[1]})`).join(", "));
console.log("Instructors: " + importRows(instructorsFile, (row) => `${row[0]} teaches ${row[1]}`).join(", "));
console.log("Class times: " + importRows(classTimesFile, (row) => `${row[0]} at ${row[1]}`).join(", "));
```

```text
Members: Maya (basic), Sam (unlimited), Leo (basic)
Instructors: Priya teaches yoga, Omar teaches spin
Class times: yoga at 07:00, spin at 12:00, HIIT at 18:00
```

```typescript
// The shape all three copies shared: skip the header and blank lines, split each line and trim its values.
// The one part that differs, turning a row into something, is handed in.
function importRows<T>(text: string, makeRow: (row: string[]) => T): T[] {
  const rows: T[] = [];
  for (const line of text.trim().split("\n").slice(1)) {
    if (line.trim() === "") { continue; }
    rows.push(makeRow(line.split(",").map((value) => value.trim())));
  }
  return rows;
}

const membersFile = "name,plan\nMaya, basic\nSam,unlimited\n\nLeo,basic";
const instructorsFile = "name,class\nPriya,yoga\nOmar, spin";
const classTimesFile = "class,time\nyoga,07:00\n\nspin,12:00\nHIIT,18:00";

console.log("Members: " + importRows(membersFile, (row) => `${row[0]} (${row[1]})`).join(", "));
console.log("Instructors: " + importRows(instructorsFile, (row) => `${row[0]} teaches ${row[1]}`).join(", "));
console.log("Class times: " + importRows(classTimesFile, (row) => `${row[0]} at ${row[1]}`).join(", "));
```

```text
Members: Maya (basic), Sam (unlimited), Leo (basic)
Instructors: Priya teaches yoga, Omar teaches spin
Class times: yoga at 07:00, spin at 12:00, HIIT at 18:00
```

Each importer is now one line, and the equipment team's will be one line too. `importRows` is a small pattern of the gym's own: the steps are fixed, and your own step is handed in as a function. You've met both halves in this course: Template Method's "same routine, your own step", and Pass 1's weekly deal passed in as a function.

![Three importers (members, instructors, class times) follow the same five steps. The first four, skip the header, skip blank lines, split at commas and trim each value, are the same every time: written once. Only the last, make a row, differs: "name (plan)", "name teaches class", "class at time"](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/87260a5acd4f46a3ab2fe18a3e402801.webp)

## How every pattern began

The 1994 book of patterns lists *known uses* for each of its patterns: real systems where the solution had already turned up. Pattern writers still use the same test: a solution counts as a pattern once it's been seen in about three places. Every pattern in this course started as somebody's third copy, written down and named. Your team's solutions are no different. The row importer is a pattern: small, local to one team, and real. The next lesson writes it down.

## When not to use it

- **When the copies are one fact, not one shape.** If the 8% sales tax is typed into two places, put it in one place now: don't wait for a third. That's the **DRY principle** ("don't repeat yourself": one piece of knowledge, one place). The rule of three is for *shapes* of code, where the second copy might still turn out different.
- **When copies only look alike.** Two importers that change for different reasons (one follows the gym's spreadsheets, one a bank's file format) should stay apart, even if they look the same today.
- **When the third copy shows they're different after all.** The rule tells you when to look closely, not what you'll find.

## Check yourself

2 questions to try on the lesson page.

## So what

When you're about to copy a solution for the third time, stop: the shape is clear now, so write the shared steps once and hand in the part that differs. That's how patterns are born, in your code as much as in the book.

## Key terms

- [Rule of Three](https://www.ask-codey.com/glossary/rule-of-three)
- [DRY Principle](https://www.ask-codey.com/glossary/dry-principle)
- [Design Pattern](https://www.ask-codey.com/glossary/design-pattern)

## Cheat sheets

- [When Repetition Becomes a Pattern: The Rule of Three](https://www.ask-codey.com/cheat-sheets/dp-rule-of-three-cheat-sheet)

Source: https://www.ask-codey.com/lessons/dp-rule-of-three
