Agile Principles, Patterns, and Practices in C#

Some simple heuristics can give you some clues about LSP violations. These heuristics all have to do with derivative classes that somehow remove functionality from their base classes. A derivative that does less than its base is usually not substitutable for that base and therefore violates LSP.

Consider Figure 10-13. The f function in Base is implemented but in Derived is degenerate. Presumably, the author of Derived found that function f had no useful purpose in a Derived. Unfortunately, the users of Base don't know that they shouldn't call f, and so there is a substitution violation.

Listing 10-13. A degenerate function in a derivative

public class Base { public virtual void f() {/*some code*/} } public class Derived : Base { public override void f() {} }

The presence of degenerate functions in derivatives is not always indicative of an LSP violation, but it's worth looking at them when they occur.

Категории