LSP – swappable objects
Turing Award winner Barbara Liskov is the creator of a rule concerning inheritance that is now commonly known as LSP. It was brought about by a question in OOP: if we can extend a class and use it in place of the class we extended, how can we be sure the new class will not break things?
We’ve seen in the previous section on DIP how we can use any class that implements an interface in place of the interface itself. We also saw how those classes can provide any implementation they like for that method. The interface itself provides no guarantees at all about what might lurk inside that implementation code.
There is, of course, a bad side to this—which LSP aims to avoid. Let’s explain this by looking at a counter-example in code. Suppose we made a new class that implemented interface Shape
, such as this one (Warning: Do NOT run the code that follows in the MaliciousShape
class!):
public class MaliciousShape implements Shape...