Skip to main content

Give an example of LSP compliance

An example of LSP compliance is a situation where a subclass extends the parent's behavior without violating its contract, and can fully substitute for the base class in client code.

Below is a correct example: the base class describes a notification interface, and subclasses implement different ways of sending it.


Base class (contract)

python
class Notifier: def send(self, message: str): raise NotImplementedError

Subclasses that follow LSP

python
class EmailNotifier(Notifier): def send(self, message: str): print(f"Sending email: {message}") class SmsNotifier(Notifier): def send(self, message: str): print(f"Sending SMS: {message}")

Why this follows LSP:

  1. The subclasses do not change the meaning of the send() method They simply implement it in their own way. The base contract: "send a message". Both subclasses follow this contract.
  2. The subclasses do not tighten input restrictions The method accepts any string - both Email and SMS accept any string.
  3. The subclasses do not weaken the guarantees of the result The base class's promise: "the send operation is performed". Both implementations fulfill this.
  4. There is no need to check the type

Client code:

python
def notify(notifier: Notifier, msg): notifier.send(msg)

Any subclass can be substituted in:

python
notify(EmailNotifier(), "Hello!") notify(SmsNotifier(), "Hello!")

And the program will work correctly and predictably, with no changes.

  1. Invariants are not violated The base class has no state at all, so descendants cannot break anything.

Summary

The EmailNotifier and SmsNotifier classes fully preserve the contract of Notifier, do not change the meaning of the behavior, and can safely be used wherever the base type is expected - this is exactly what correct LSP compliance looks like.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.