Course contentsShow
← Software Engineering
Lesson 211 of 1,9336. SOLID PrinciplesFree lesson

LSP Violations: Weakening Postconditions

A subclass that provides weaker guarantees or returns less than expected violates the parent's contract.

LSP Violations: Weakening Postconditions

What You'll Learn

You'll learn how a subclass breaks the Liskov Substitution Principle when it promises less or delivers weaker results than its parent class.

Understanding Postconditions

A postcondition is a guarantee a method makes about what will be true after it executes. It's the promise the method keeps with its callers.

When a parent class method promises to return something or ensure a certain state, every subclass must uphold or strengthen that promise—never weaken it.

What Does "Weakening" Mean?

Imagine a parent class BankAccount with a withdraw() method that guarantees: "After withdrawal, the balance will be reduced by exactly the requested amount."

If a subclass SpecialAccount overrides this and sometimes doesn't reduce the balance (maybe it fails silently), it has weakened the postcondition. The caller expected a guarantee but got less.

The Contract Violation

Think of it like ordering a pizza. The restaurant (parent class) promises: "You'll receive a hot, complete pizza." If a franchise (subclass) sometimes delivers cold pizza or pizza with missing slices, they've weakened the promise. Customers who trusted the brand's guarantee are now disappointed.

Code expecting the parent's guarantees will break when given the subclass. This violates LSP because substitution no longer works safely.

Common Examples

  • A parent method guarantees it returns a non-null value; the subclass returns null
  • A parent sorts a list completely; the subclass only partially sorts it
  • A parent validates and saves data; the subclass skips validation

Key Takeaway: Subclasses must provide at least the same guarantees as their parent—never less. Weakening postconditions breaks the trust that makes polymorphism safe and reliable.