Can anyone provide an example of the Liskov Substitution Principle (LSP) using Vehicles?

For me, this 1996 Quote from Uncle Bob (Robert C Martin) summarises the LSP best: Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it. In recent times, as an alternative to inheritance abstractions based on sub-classing from a (usually abstract) base/super class, we …

Read more

How do I avoid breaking the Liskov substitution principle with a class that implements multiple interfaces?

I’m aware that I could have a wrapper interface that extends both interfaces, but then I could end up with multiple interfaces to cater for all the possible permutations of interfaces that can be implemented by the same class I suspect that if you’re finding that lots of your classes implement different combinations of interfaces …

Read more

Do Collections.unmodifiableXXX methods violate LSP? [closed]

LSP says that every subclass must obey the same contracts as the superclass. Wether or not this is the case for Collections.unmodifiableXXX() thus depends on how this contract reads. The objects returned by Collections.unmodifiableXXX() throw an exception if one tries to call any modifying method upon them. For instance, if add() is called, an UnsupportedOperationException …

Read more

Liskov substitution principle – no overriding/virtual methods?

Subclasses overriding methods in the base class are totally allowed by the Liskov Substituion Principle. This might be simplifying it too much, but I remember it as “a subclass should require nothing more and promise nothing less” If a client is using a superclass ABC with a method something(int i), then the client should be …

Read more

Any good examples of inheriting from a concrete class? [closed]

You often have a skeletal implementations for an interface I. If you can offer extensibility without abstract methods (e.g. via hooks), it is preferable to have a non-abstract skeletal class because you can instantiate it. An example would be a forwarding wrapper classes, to be able to forward to another object of a concrete class …

Read more

Is deriving square from rectangle a violation of Liskov’s Substitution Principle? [closed]

The answer depends on mutability. If your rectangle and square classes are immutable, then Square is really a subtype of Rectangle and it’s perfectly OK to derive first from second. Otherwise, Rectangle and Square could both expose an IRectangle with no mutators, but deriving one from the other is wrong since neither type is properly …

Read more