# Liskov Substitution: No Surprises from a Stand-In

When a pass/fail course is written as a kind of course and then throws when asked for a letter grade, every report card with art on it stops; the Liskov substitution principle says a subclass must keep every promise its parent makes, so it can stand in anywhere the parent is expected, with no surprises.

Journeyman · OOP · Updated November 17, 2026

By Gregor Dzierzon

## After this lesson you can

- Check whether a subclass keeps every promise its parent makes, so it can stand in without surprises
- Fix a broken stand-in by changing the promise or the class tree, not by checking types

## Key takeaways

- Anywhere code expects a parent class, any of its subclasses must work, with no surprises: that's Liskov substitution.
- A subclass breaks it when it throws for a method the parent promises, quietly does nothing, or returns a value that isn't true.
- The usual sign is code that has to check which subclass it was handed before calling a method.
- The fix is a promise every kind can really keep, or a class tree where the child isn't pretending to be the parent.

**Before this:** *Inheritance and Composition: Is-a and Has-a*, and *Open/Closed: Add, Don't Edit*.

Northside High made art pass/fail this year. A developer added it the way most of us would: a pass/fail course *is a* course, so `PassFailCourse` became a subclass of `Course`. It can't give a letter grade, so it throws an error when asked for one. The first report card with art on it stopped halfway through. This lesson is about the promise that subclass broke.

## The symptom: one stand-in stops the whole report card

Every `Course` promises a `LetterGrade`. The report line asks each course for one:

```csharp
try
{
    Console.WriteLine(ReportLine("Maya", new List<Course> { new Course("Math", 93), new Course("Science", 85) }));
    Console.WriteLine(ReportLine("Maya", new List<Course> { new Course("Math", 93), new PassFailCourse("Art", 95) }));
}
catch (InvalidOperationException error)
{
    Console.WriteLine("The report card stopped: " + error.Message);
}

string ReportLine(string name, List<Course> courses) =>
    name + ": " + string.Join(", ", courses.Select(course => course.Name + " " + course.LetterGrade()));

class Course
{
    public string Name { get; }
    public int Score { get; }

    public Course(string name, int score)
    {
        Name = name;
        Score = score;
    }

    public virtual string LetterGrade()
    {
        if (Score >= 90) { return "A"; }
        if (Score >= 80) { return "B"; }
        if (Score >= 70) { return "C"; }
        if (Score >= 60) { return "D"; }
        return "F";
    }
}

// A pass/fail course "is a" course... until someone asks it for a letter grade.
class PassFailCourse : Course
{
    public PassFailCourse(string name, int score) : base(name, score) { }

    public override string LetterGrade() => throw new InvalidOperationException(Name + " is pass/fail and has no letter grade");
}
```

```text
Maya: Math A, Science B
The report card stopped: Art is pass/fail and has no letter grade
```

```java
class Course {
    final String name;
    final int score;

    Course(String name, int score) {
        this.name = name;
        this.score = score;
    }

    String letterGrade() {
        if (score >= 90) { return "A"; }
        if (score >= 80) { return "B"; }
        if (score >= 70) { return "C"; }
        if (score >= 60) { return "D"; }
        return "F";
    }
}

// A pass/fail course "is a" course... until someone asks it for a letter grade.
class PassFailCourse extends Course {
    PassFailCourse(String name, int score) { super(name, score); }

    String letterGrade() {
        throw new IllegalStateException(name + " is pass/fail and has no letter grade");
    }
}

String reportLine(String name, List<Course> courses) {
    List<String> grades = new ArrayList<>();
    for (Course course : courses) { grades.add(course.name + " " + course.letterGrade()); }
    return name + ": " + String.join(", ", grades);
}

void main() {
    try {
        IO.println(reportLine("Maya", List.of(new Course("Math", 93), new Course("Science", 85))));
        IO.println(reportLine("Maya", List.of(new Course("Math", 93), new PassFailCourse("Art", 95))));
    } catch (IllegalStateException error) {
        IO.println("The report card stopped: " + error.getMessage());
    }
}
```

```text
Maya: Math A, Science B
The report card stopped: Art is pass/fail and has no letter grade
```

```python
class Course:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def letter_grade(self):
        if self.score >= 90:
            return "A"
        if self.score >= 80:
            return "B"
        if self.score >= 70:
            return "C"
        if self.score >= 60:
            return "D"
        return "F"


class PassFailCourse(Course):
    """A pass/fail course "is a" course... until someone asks it for a letter grade."""

    def letter_grade(self):
        raise ValueError(self.name + " is pass/fail and has no letter grade")


def report_line(name, courses):
    return name + ": " + ", ".join(course.name + " " + course.letter_grade() for course in courses)


try:
    print(report_line("Maya", [Course("Math", 93), Course("Science", 85)]))
    print(report_line("Maya", [Course("Math", 93), PassFailCourse("Art", 95)]))
except ValueError as error:
    print("The report card stopped: " + str(error))
```

```text
Maya: Math A, Science B
The report card stopped: Art is pass/fail and has no letter grade
```

```javascript
class Course {
  constructor(name, score) {
    this.name = name;
    this.score = score;
  }

  letterGrade() {
    if (this.score >= 90) { return "A"; }
    if (this.score >= 80) { return "B"; }
    if (this.score >= 70) { return "C"; }
    if (this.score >= 60) { return "D"; }
    return "F";
  }
}

// A pass/fail course "is a" course... until someone asks it for a letter grade.
class PassFailCourse extends Course {
  letterGrade() {
    throw new Error(this.name + " is pass/fail and has no letter grade");
  }
}

function reportLine(name, courses) {
  return name + ": " + courses.map((course) => course.name + " " + course.letterGrade()).join(", ");
}

try {
  console.log(reportLine("Maya", [new Course("Math", 93), new Course("Science", 85)]));
  console.log(reportLine("Maya", [new Course("Math", 93), new PassFailCourse("Art", 95)]));
} catch (error) {
  console.log("The report card stopped: " + error.message);
}
```

```text
Maya: Math A, Science B
The report card stopped: Art is pass/fail and has no letter grade
```

```typescript
class Course {
  name: string;
  score: number;

  constructor(name: string, score: number) {
    this.name = name;
    this.score = score;
  }

  letterGrade(): string {
    if (this.score >= 90) { return "A"; }
    if (this.score >= 80) { return "B"; }
    if (this.score >= 70) { return "C"; }
    if (this.score >= 60) { return "D"; }
    return "F";
  }
}

// A pass/fail course "is a" course... until someone asks it for a letter grade.
class PassFailCourse extends Course {
  letterGrade(): string {
    throw new Error(this.name + " is pass/fail and has no letter grade");
  }
}

function reportLine(name: string, courses: Course[]): string {
  return name + ": " + courses.map((course) => course.name + " " + course.letterGrade()).join(", ");
}

try {
  console.log(reportLine("Maya", [new Course("Math", 93), new Course("Science", 85)]));
  console.log(reportLine("Maya", [new Course("Math", 93), new PassFailCourse("Art", 95)]));
} catch (error) {
  console.log("The report card stopped: " + (error as Error).message);
}
```

```text
Maya: Math A, Science B
The report card stopped: Art is pass/fail and has no letter grade
```

Nothing is wrong with `ReportLine`: it asked a `Course` for what every `Course` promises. The surprise came from the stand-in.

- **The symptom:** code that works with every `Course` breaks when handed one particular subclass. Here it throws; in other code the stand-in might quietly do nothing, or return a value that isn't true.
- **The cause:** `PassFailCourse` claims to be a `Course` but can't keep one of `Course`'s promises. Its parent says "I can give a letter grade"; the child can't.

## What would you try?

**Check the type first:** `if (course is PassFailCourse) …` in `ReportLine`. It works, and now `ReportLine` knows every kind of course by name. The next kind that can't give a letter (an audit course, a credit-only course) needs another check, here and in every other place that asks for a letter: the growing `if` chain, and an edit to trusted code every time, which is what *Open/Closed* warned about.

**Catch the error and skip the course.** The report card finishes, and art is missing from it. The surprise is quieter, which is worse: a family wonders why art isn't on the report.

**Have `PassFailCourse` return `"A"` for a pass.** The report card prints, and it says something untrue. A college reading the transcript would count it as an A.

All three work around the stand-in instead of asking why it can't stand in.

## The idea: a stand-in keeps every promise

Think of a substitute teacher. When your teacher is out, the substitute follows the same lesson plan, takes attendance, and gives the quiz on the same day. That's what makes a substitute a substitute: the class goes on with no surprises. A substitute who canceled the quiz and played a movie would be standing in the teacher's place without keeping the teacher's promises.

![A substitute teacher at the front of a classroom, holding the regular teacher's lesson plan open and following it, with the same quiz handed out on each desk](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/160eda24169547f280fe76c11148ef8e.webp)

In 1987, the computer scientist Barbara Liskov put this into a rule that now carries her name, the **Liskov substitution principle**: **anywhere code expects a parent class, it must be able to use any of its subclasses, with no surprises.** A subclass may do things its own way, but it must keep every promise the parent makes: no new errors, no ignored methods, no answers that aren't true.

So the question is: what can *every* course really promise? Not a letter grade. Every course can promise "a grade to print on the report card". Make that the promise, and let each kind keep it its own way:

```csharp
Console.WriteLine(ReportLine("Maya", new List<ICourse> { new LetterCourse("Math", 93), new LetterCourse("Science", 85) }));
Console.WriteLine(ReportLine("Maya", new List<ICourse> { new LetterCourse("Math", 93), new PassFailCourse("Art", 95) }));

string ReportLine(string name, List<ICourse> courses) =>
    name + ": " + string.Join(", ", courses.Select(course => course.Name + " " + course.Grade()));

// The promise every course can really keep: a grade to print.
interface ICourse
{
    string Name { get; }
    string Grade();
}

class LetterCourse : ICourse
{
    private int score;

    public LetterCourse(string name, int score)
    {
        Name = name;
        this.score = score;
    }

    public string Name { get; }

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

class PassFailCourse : ICourse
{
    private int score;

    public PassFailCourse(string name, int score)
    {
        Name = name;
        this.score = score;
    }

    public string Name { get; }

    public string Grade() => score >= 60 ? "Pass" : "Fail";
}
```

```text
Maya: Math A, Science B
Maya: Math A, Art Pass
```

```java
// The promise every course can really keep: a grade to print.
interface Course {
    String name();
    String grade();
}

record LetterCourse(String name, int score) implements Course {
    public String grade() {
        if (score >= 90) { return "A"; }
        if (score >= 80) { return "B"; }
        if (score >= 70) { return "C"; }
        if (score >= 60) { return "D"; }
        return "F";
    }
}

record PassFailCourse(String name, int score) implements Course {
    public String grade() { return score >= 60 ? "Pass" : "Fail"; }
}

String reportLine(String name, List<Course> courses) {
    List<String> grades = new ArrayList<>();
    for (Course course : courses) { grades.add(course.name() + " " + course.grade()); }
    return name + ": " + String.join(", ", grades);
}

void main() {
    IO.println(reportLine("Maya", List.of(new LetterCourse("Math", 93), new LetterCourse("Science", 85))));
    IO.println(reportLine("Maya", List.of(new LetterCourse("Math", 93), new PassFailCourse("Art", 95))));
}
```

```text
Maya: Math A, Science B
Maya: Math A, Art Pass
```

```python
from abc import ABC, abstractmethod


class Course(ABC):
    """The promise every course can really keep: a grade to print."""

    def __init__(self, name, score):
        self.name = name
        self.score = score

    @abstractmethod
    def grade(self):
        ...


class LetterCourse(Course):
    def grade(self):
        if self.score >= 90:
            return "A"
        if self.score >= 80:
            return "B"
        if self.score >= 70:
            return "C"
        if self.score >= 60:
            return "D"
        return "F"


class PassFailCourse(Course):
    def grade(self):
        return "Pass" if self.score >= 60 else "Fail"


def report_line(name, courses):
    return name + ": " + ", ".join(course.name + " " + course.grade() for course in courses)


print(report_line("Maya", [LetterCourse("Math", 93), LetterCourse("Science", 85)]))
print(report_line("Maya", [LetterCourse("Math", 93), PassFailCourse("Art", 95)]))
```

```text
Maya: Math A, Science B
Maya: Math A, Art Pass
```

```javascript
// The promise every course can really keep: a name, and a grade() to print.
class LetterCourse {
  constructor(name, score) {
    this.name = name;
    this.score = score;
  }

  grade() {
    if (this.score >= 90) { return "A"; }
    if (this.score >= 80) { return "B"; }
    if (this.score >= 70) { return "C"; }
    if (this.score >= 60) { return "D"; }
    return "F";
  }
}

class PassFailCourse {
  constructor(name, score) {
    this.name = name;
    this.score = score;
  }

  grade() { return this.score >= 60 ? "Pass" : "Fail"; }
}

function reportLine(name, courses) {
  return name + ": " + courses.map((course) => course.name + " " + course.grade()).join(", ");
}

console.log(reportLine("Maya", [new LetterCourse("Math", 93), new LetterCourse("Science", 85)]));
console.log(reportLine("Maya", [new LetterCourse("Math", 93), new PassFailCourse("Art", 95)]));
```

```text
Maya: Math A, Science B
Maya: Math A, Art Pass
```

```typescript
// The promise every course can really keep: a grade to print.
interface Course {
  name: string;
  grade(): string;
}

class LetterCourse implements Course {
  name: string;
  score: number;

  constructor(name: string, score: number) {
    this.name = name;
    this.score = score;
  }

  grade(): string {
    if (this.score >= 90) { return "A"; }
    if (this.score >= 80) { return "B"; }
    if (this.score >= 70) { return "C"; }
    if (this.score >= 60) { return "D"; }
    return "F";
  }
}

class PassFailCourse implements Course {
  name: string;
  score: number;

  constructor(name: string, score: number) {
    this.name = name;
    this.score = score;
  }

  grade(): string { return this.score >= 60 ? "Pass" : "Fail"; }
}

function reportLine(name: string, courses: Course[]): string {
  return name + ": " + courses.map((course) => course.name + " " + course.grade()).join(", ");
}

console.log(reportLine("Maya", [new LetterCourse("Math", 93), new LetterCourse("Science", 85)]));
console.log(reportLine("Maya", [new LetterCourse("Math", 93), new PassFailCourse("Art", 95)]));
```

```text
Maya: Math A, Science B
Maya: Math A, Art Pass
```

The first line is the same, and the second one finishes: `Art Pass`. `ReportLine` still checks no types and knows no kinds; it asks each course for its grade. `PassFailCourse` is no longer pretending to be a letter-grade course. Both are kinds of *course*, and both keep everything a course promises. An audit course next year is one more class, and it can stand in on day one.

**Try it.** Add an `AuditCourse` whose grade is always `Audit`, and print a report line with it. `ReportLine` shouldn't need a single change.

**Where the languages differ.** Java writes each course as a `record` that keeps the `Course` interface, which gives it `name()` for free. JavaScript has no interface; both classes have a `name` and a `grade()`, and that's the promise.

## How to spot a broken stand-in

Look for a subclass that:

- **throws** "not supported" or "not allowed" for a method its parent has;
- **does nothing** in a method its parent promises will do something;
- **returns a value that isn't true** (a 0 that means "doesn't apply", an "A" that means "pass");
- **needs callers to check its type** before they use it.

Any of these means the child is standing in without keeping the parent's promises.

## When to bend it

- **Even standard libraries bend it, and say so.** Java's `List.of(…)` gives a list that throws if you call `add`, and C#'s read-only collections do the same. They document it loudly, so nobody is surprised. If you bend it, be that loud.
- **A small class tree that you own end to end** may be fine with a documented exception, while it stays small.
- **In your textbook,** the classic example is a square written as a kind of rectangle: setting a square's width changes its height too, which surprises code that expects a rectangle. Same idea, different shapes.

## Check yourself

2 questions to try on the lesson page.

## So what

"Is a" in real life doesn't always mean "is a" in code. A subclass earns its place by keeping every promise its parent makes; when it can't, change the promise to one every kind can keep.

## Key terms

- [Liskov Substitution Principle](https://www.ask-codey.com/glossary/liskov-substitution-principle)
- [Inheritance](https://www.ask-codey.com/glossary/inheritance-oop)
- [Polymorphism](https://www.ask-codey.com/glossary/polymorphism-oop)

## Cheat sheets

- [Liskov Substitution: No Surprises from a Stand-In](https://www.ask-codey.com/cheat-sheets/dp-liskov-substitution-cheat-sheet)

Source: https://www.ask-codey.com/lessons/dp-liskov-substitution
