A Typical Violation
Further information: Circle-ellipse problemA typical example that violates LSP is a Square class that derives from a Rectangle class, assuming getter and setter methods exist for both width and height. The Square class always assumes that the width is equal with the height. If a Square object is used in a context where a Rectangle is expected, unexpected behavior may occur because the dimensions of a Square cannot (or rather should not) be modified independently. This problem cannot be easily fixed: if we can modify the setter methods in the Square class so that they preserve the Square invariant (i.e., keep the dimensions equal), then these methods will weaken (violate) the postconditions for the Rectangle setters, which state that dimensions can be modified independently. Violations of LSP, like this one, may or may not be a problem in practice, depending on the postconditions or invariants that are actually expected by the code that uses classes violating LSP. Mutability is a key issue here. If Square and Rectangle had only getter methods (i.e., they were immutable objects), then no violation of LSP could occur.
Read more about this topic: Liskov Substitution Principle
Famous quotes containing the words typical and/or violation:
“Compare the history of the novel to that of rock n roll. Both started out a minority taste, became a mass taste, and then splintered into several subgenres. Both have been the typical cultural expressions of classes and epochs. Both started out aggressively fighting for their share of attention, novels attacking the drama, the tract, and the poem, rock attacking jazz and pop and rolling over classical music.”
—W. T. Lhamon, U.S. educator, critic. Material Differences, Deliberate Speed: The Origins of a Cultural Style in the American 1950s, Smithsonian (1990)
“The urgent consideration of the public safety may undoubtedly authorise the violation of every positive law. How far that or any other consideration may operate to dissolve the natural obligations of humanity and justice, is a doctrine of which I still desire to remain ignorant.”
—Edward Gibbon (17371794)