Monday, July 28, 2008

The Liskov Substitution Principle (LSP)

Subtypes must be substitutable for their base types. It must make sense for "is-a" testing. For example, sedan IS A car, which makes sense, so sedan is substitutable for car.

Inheritance (and the LSP) indicate that any method on base class should be able to used on the sub types. For example, car has a method called startEngine(), which also makes sense to let sedan have this method.

Delegation
If you need to use functionality in another class, but you don't want to change that functionality, consider using delegation instead of inheritance.

Composition
You can use composition to assemble behaviors from other classes. Here is one example:

Suppose we wanted to develop a Weapon interface, and then create several implementations of that interface that all behave differently. Now we need to use the behaviour in our Unit Class. But we don't want to tie to a specific implementation of Weapon. Composition is most powerful when you want to use behavior defined in an interface, and then choose from a variety of implementations of that interface, at both compile time and run time. Pizza is actually a great example of composition. It is composed of different ingredients, but you can swap out different ingredients without affecting the overall pizza slice.
When an object is composed of other objects, and the owning object is destroyed, the objects that are part of the composition go away, too. The behaviors in a composition do not exist outside of the composition itself.

Aggregation
When you want the benefits of composition, but you are using behavior form an object that does not exist outside your object, use aggregation

If you favor delegation composition, and aggregation over inheritance, your software will usually be more flexible, and easier to maintain, extend and reuse.

The LSP is about when to subclass. If your subclass really is substitutable for its base type, then use inheritance. If not, then you might look at other OO solutions like delegation, composition or aggregation.

No comments:

Post a Comment