Liskov Substitution Principle (L)

This is a slight variation of the Open/Closed Principle, and Uncle Bob states it as follows:

"Derived types must be substitutable for their base types."

This principle is called Liskov because it was first written by Barbara Liskov:

"What is wanted here is something like the following substitution property: If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2—then S is a subtype of T.

The crux of the principle is that derived classes must be usable through the base class interface without the need for the client to know the specific derived class.

As we have seen earlier, in Go, object orientation is enabled by composition (prototype pattern), rather than class hierarchies. So, though this principle does not imply as strongly as other languages, it does give us guidance to interface design: the interface should be able to suffice for all structs that implement that interface.

A good example for application of this principle is the previous example of cancellation fee calculation. This enables a clear separation of concerns:

  • The client who wants to compute the cancellation fee for a trip does not care about the specific type of reservations in the trip.
  •  The trip's code does not know how each reservation computes the cancellation fee.

If, however, the client code tries to check the type of derived class (through Reflection for example) to explicitly call the cancellation-fee method on each (concrete) type of reservation, then the abstraction breaks down. The Liskov Substitution Principle (LSP) precisely advises against doing this type of thing.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset