Sobes.tech
Senior

Provide a more realistic example of LSP violation from production.

sobes.tech AI

Answer from AI

An example of violating the Liskov Substitution Principle (LSP) from real production might look like this:

There is a base class PaymentProcessor with a method processPayment(amount) that handles payments.

public class PaymentProcessor {
    public void processPayment(double amount) {
        // General payment processing logic
    }
}

A subclass FreePaymentProcessor is intended for free services and overrides the method, but does not perform processing, instead it throws an exception:

public class FreePaymentProcessor extends PaymentProcessor {
    @Override
    public void processPayment(double amount) {
        throw new UnsupportedOperationException("Free payments are not processed");
    }
}

This violates LSP because a client using PaymentProcessor expects any subclass to correctly handle payments, but here the subclass breaks the contract by throwing an exception. In production, this can lead to unexpected failures.

It would be better to reconsider the hierarchy or use composition to avoid creating subclasses that do not support the base functionality.