<p>I have heard that the Liskov Substitution  Principle (LSP) is a fundamental principle of object oriented design. What is it and what are some examples of its use?</p>

[{'answer_id': 56884, 'author': 'Tom Hawtin - tackline', 'author_id': 4725, 'author_profile': 'https://Stackoverflow.com/users/4725', 'pm_score': 2, 'selected': False, 'text': '<p>Would implementing ThreeDBoard in terms of an array of Board be that useful?</p>\n\n<p>Perhaps you may want to treat slices of ThreeDBoard in various planes as a Board. In that case you may want to abstract out an interface (or abstract class) for Board to allow for multiple implementations.</p>\n\n<p>In terms of external interface, you might want to factor out a Board interface for both TwoDBoard and ThreeDBoard (although none of the above methods fit).</p>\n'}, {'answer_id': 56904, 'author': 'NotMyself', 'author_id': 303, 'author_profile': 'https://Stackoverflow.com/users/303', 'pm_score': 9, 'selected': False, 'text': '<p>The Liskov Substitution Principle (LSP, <a href="/questions/tagged/lsp" class="post-tag" title="show questions tagged &#39;lsp&#39;" rel="tag">lsp</a>) is a concept in Object Oriented Programming that states:</p>\n\n<blockquote>\n  <p>Functions that use pointers or\n  references to base classes must be\n  able to use objects of derived classes\n  without knowing it.</p>\n</blockquote>\n\n<p>At its heart LSP is about interfaces and contracts as well as how to decide when to extend a class vs. use another strategy such as composition to achieve your goal.</p>\n\n<p>The most effective way I have seen to illustrate this point was in <a href="http://oreilly.com/catalog/9780596008673/index.html" rel="noreferrer">Head First OOA&amp;D</a>. They present a scenario where you are a developer on a project to build a framework for strategy games.</p>\n\n<p>They present a class that represents a board that looks like this:</p>\n\n<p><img src="https://oncodebynotmyself.files.wordpress.com/2011/03/board_thumb.png" alt="Class Diagram"></p>\n\n<p>All of the methods take X and Y coordinates as parameters to locate the tile position in the two-dimensional array of <code>Tiles</code>. This will allow a game developer to manage units in the board during the course of the game.</p>\n\n<p>The book goes on to change the requirements to say that the game frame work must also support 3D game boards to accommodate games that have flight. So a <code>ThreeDBoard</code> class is introduced that extends <code>Board</code>.</p>\n\n<p>At first glance this seems like a good decision. <code>Board</code> provides both the <code>Height</code> and <code>Width</code> properties and <code>ThreeDBoard</code> provides the Z axis.</p>\n\n<p>Where it breaks down is when you look at all the other members inherited from <code>Board</code>. The methods for <code>AddUnit</code>, <code>GetTile</code>, <code>GetUnits</code> and so on, all take both X and Y parameters in the <code>Board</code> class but the <code>ThreeDBoard</code> needs a Z parameter as well.</p>\n\n<p>So you must implement those methods again with a Z parameter. The Z parameter has no context to the <code>Board</code> class and the inherited methods from the <code>Board</code> class lose their meaning. A unit of code attempting to use the <code>ThreeDBoard</code> class as its base class <code>Board</code> would be very out of luck.</p>\n\n<p>Maybe we should find another approach. Instead of extending <code>Board</code>, <code>ThreeDBoard</code> should be composed of <code>Board</code> objects. One <code>Board</code> object per unit of the Z axis.</p>\n\n<p>This allows us to use good object oriented principles like encapsulation and reuse and doesn’t violate LSP.</p>\n'}, {'answer_id': 56990, 'author': 'Chris Ammerman', 'author_id': 2729, 'author_profile': 'https://Stackoverflow.com/users/2729', 'pm_score': 4, 'selected': False, 'text': '<blockquote>\n  <p>Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.</p>\n</blockquote>\n\n<p>When I first read about LSP, I assumed that this was meant in a very strict sense, essentially equating it to interface implementation and type-safe casting.  Which would mean that LSP is either ensured or not by the language itself.  For example, in this strict sense, ThreeDBoard is certainly substitutable for Board, as far as the compiler is concerned.</p>\n\n<p>After reading up more on the concept though I found that LSP is generally interpreted more broadly than that.</p>\n\n<p>In short, what it means for client code to "know" that the object behind the pointer is of a derived type rather than the pointer type is not restricted to type-safety.  Adherence to LSP is also testable through probing the objects actual behavior.  That is, examining the impact of an object\'s state and method arguments on the results of the method calls, or the types of exceptions thrown from the object.</p>\n\n<p>Going back to the example again, <strong>in theory</strong> the Board methods can be made to work just fine on ThreeDBoard.  In practice however, it will be very difficult to prevent differences in behavior that client may not handle properly, without hobbling the functionality that ThreeDBoard is intended to add.</p>\n\n<p>With this knowledge in hand, evaluating LSP adherence can be a great tool in determining when composition is the more appropriate mechanism for extending existing functionality, rather than inheritance.</p>\n'}, {'answer_id': 58967, 'author': 'Phillip Wells', 'author_id': 3012, 'author_profile': 'https://Stackoverflow.com/users/3012', 'pm_score': 6, 'selected': False, 'text': '<p>Robert Martin has an excellent <a href="http://web.archive.org/web/20151128004108/http://www.objectmentor.com/resources/articles/lsp.pdf" rel="noreferrer">paper on the Liskov Substitution Principle</a>. It discusses subtle and not-so-subtle ways in which the principle may be violated.</p>\n\n<p>Some relevant parts of the paper (note that the second example is heavily condensed):</p>\n\n<blockquote>\n  <h1>A Simple Example of a Violation of LSP</h1>\n  \n  <p>One of the most glaring violations of this principle is the use of C++\n  Run-Time Type Information (RTTI) to select a function based upon the\n  type of an object. i.e.:</p>\n  \n  \n\n<pre><code>void DrawShape(const Shape&amp; s)\n{\n  if (typeid(s) == typeid(Square))\n    DrawSquare(static_cast&lt;Square&amp;&gt;(s)); \n  else if (typeid(s) == typeid(Circle))\n    DrawCircle(static_cast&lt;Circle&amp;&gt;(s));\n}\n</code></pre>\n  \n  <p>Clearly the <code>DrawShape</code> function is badly formed. It must know about\n  every possible derivative of the <code>Shape</code> class, and it must be changed\n  whenever new derivatives of <code>Shape</code> are created. Indeed, many view the structure of this function as anathema to Object Oriented Design.</p>\n  \n  <h1>Square and Rectangle, a More Subtle Violation.</h1>\n  \n  <p>However, there are other, far more subtle, ways of violating the LSP.\n  Consider an application which uses the <code>Rectangle</code> class as described\n  below:</p>\n  \n  <pre><code>class Rectangle\n{\n  public:\n    void SetWidth(double w) {itsWidth=w;}\n    void SetHeight(double h) {itsHeight=w;}\n    double GetHeight() const {return itsHeight;}\n    double GetWidth() const {return itsWidth;}\n  private:\n    double itsWidth;\n    double itsHeight;\n};\n</code></pre>\n  \n  <p>[...] Imagine that one day the users demand the ability to manipulate\n  squares in addition to rectangles. [...]</p>\n  \n  <p>Clearly, a square is a rectangle for all normal intents and purposes.\n  Since the ISA relationship holds, it is logical to model the <code>Square</code>\n  class as being derived from <code>Rectangle</code>. [...]</p>\n  \n  <p><code>Square</code> will inherit the <code>SetWidth</code> and <code>SetHeight</code> functions. These\n  functions are utterly inappropriate for a <code>Square</code>, since the width and\n  height of a square are identical. This should be a significant clue\n  that there is a problem with the design. However, there is a way to\n  sidestep the problem. We could override <code>SetWidth</code> and <code>SetHeight</code> [...]</p>\n  \n  <p>But consider the following function:</p>\n  \n  <pre><code>void f(Rectangle&amp; r)\n{\n  r.SetWidth(32); // calls Rectangle::SetWidth\n}\n</code></pre>\n  \n  <p>If we pass a reference to a <code>Square</code> object into this function, the\n  <code>Square</code> object will be corrupted because the height won’t be changed.\n  This is a clear violation of LSP. The function does not work for\n  derivatives of its arguments. </p>\n  \n  <p>[...]</p>\n</blockquote>\n'}, {'answer_id': 59006, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 7, 'selected': False, 'text': '<p>LSP concerns invariants.</p>\n<p>The classic example is given by the following pseudo-code declaration (implementations omitted):</p>\n<pre><code>class Rectangle {\n    int getHeight()\n    void setHeight(int value) {\n        postcondition: width didn’t change\n    }\n    int getWidth()\n    void setWidth(int value) {\n        postcondition: height didn’t change\n    }\n}\n\nclass Square extends Rectangle { }\n</code></pre>\n<p>Now we have a problem although the interface matches. The reason is that we have violated invariants stemming from the mathematical definition of squares and rectangles. The way getters and setters work, a <code>Rectangle</code> should satisfy the following invariant:</p>\n<pre><code>void invariant(Rectangle r) {\n    r.setHeight(200)\n    r.setWidth(100)\n    assert(r.getHeight() == 200 and r.getWidth() == 100)\n}\n</code></pre>\n<p>However, this invariant (as well as the explicit postconditions) <em>must</em> be violated by a correct implementation of <code>Square</code>, therefore it is not a valid substitute of <code>Rectangle</code>.</p>\n'}, {'answer_id': 274990, 'author': 'Charlie Martin', 'author_id': 35092, 'author_profile': 'https://Stackoverflow.com/users/35092', 'pm_score': 5, 'selected': False, 'text': '<p>The LSP is a rule about the contract of the clases: if a base class satisfies a contract, then by the LSP derived classes must also satisfy that contract.</p>\n\n<p>In Pseudo-python</p>\n\n<pre><code>class Base:\n   def Foo(self, arg): \n       # *... do stuff*\n\nclass Derived(Base):\n   def Foo(self, arg):\n       # *... do stuff*\n</code></pre>\n\n<p>satisfies LSP if every time you call Foo on a Derived object, it gives exactly the same results as calling Foo on a Base object, as long as arg is the same.</p>\n'}, {'answer_id': 584732, 'author': 'm-sharp', 'author_id': 28678, 'author_profile': 'https://Stackoverflow.com/users/28678', 'pm_score': 11, 'selected': True, 'text': '<p>A great example illustrating LSP (given by Uncle Bob in a podcast I heard recently) was how sometimes something that sounds right in natural language doesn\'t quite work in code.</p>\n<p>In mathematics, a <code>Square</code> is a <code>Rectangle</code>. Indeed it is a specialization of a rectangle. The &quot;is a&quot; makes you want to model this with inheritance. However if in code you made <code>Square</code> derive from <code>Rectangle</code>, then a <code>Square</code> should be usable anywhere you expect a <code>Rectangle</code>. This makes for some strange behavior.</p>\n<p>Imagine you had <code>SetWidth</code> and <code>SetHeight</code> methods on your <code>Rectangle</code> base class; this seems perfectly logical. However if your <code>Rectangle</code> reference pointed to a <code>Square</code>, then <code>SetWidth</code> and <code>SetHeight</code> doesn\'t make sense because setting one would change the other to match it. In this case <code>Square</code> fails the Liskov Substitution Test with <code>Rectangle</code> and the abstraction of having <code>Square</code> inherit from <code>Rectangle</code> is a bad one.</p>\n<p><a href="https://i.stack.imgur.com/ilxzO.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/ilxzO.jpg" alt="enter image description here" /></a></p>\n<p>Y\'all should check out the other priceless <a href="https://www.globalnerdy.com/2009/07/15/the-solid-principles-explained-with-motivational-posters/" rel="noreferrer">SOLID Principles Explained With Motivational Posters</a>.</p>\n'}, {'answer_id': 712107, 'author': 'Damien Pollet', 'author_id': 63112, 'author_profile': 'https://Stackoverflow.com/users/63112', 'pm_score': 3, 'selected': False, 'text': '<p>This formulation of the LSP is way too strong:</p>\n\n<blockquote>\n  <p>If for each object o1 of type S there is an object o2 of type T such that for all programs P deﬁned in terms of T, the behavior of P is unchanged when o1 is substituted for o2, then S is a subtype of T.</p>\n</blockquote>\n\n<p>Which basically means that S is another, completely encapsulated implementation of the exact same thing as T. And I could be bold and decide that performance is part of the behavior of P...</p>\n\n<p>So, basically, any use of late-binding violates the LSP. It\'s the whole point of OO to to obtain a different behavior when we substitute an object of one kind for one of another kind!</p>\n\n<p>The formulation cited <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="noreferrer">by wikipedia</a> is better since the property depends on the context and does not necessarily include the whole behavior of the program.</p>\n'}, {'answer_id': 8279878, 'author': 'Shelby Moore III', 'author_id': 615784, 'author_profile': 'https://Stackoverflow.com/users/615784', 'pm_score': 5, 'selected': False, 'text': '<p>LSP is necessary where some code thinks it is calling the methods of a type <code>T</code>, and may unknowingly call the methods of a type <code>S</code>, where <code>S extends T</code> (i.e. <code>S</code> inherits, derives from, or is a subtype of, the supertype <code>T</code>).</p>\n\n<p>For example, this occurs where a function with an input parameter of type <code>T</code>, is called (i.e. invoked) with an argument value of type <code>S</code>. Or, where an identifier of type <code>T</code>, is  assigned a value of type <code>S</code>.</p>\n\n<pre class="lang-scala prettyprint-override"><code>val id : T = new S() // id thinks it\'s a T, but is a S\n</code></pre>\n\n<p>LSP requires the expectations (i.e. invariants) for methods of type <code>T</code> (e.g. <code>Rectangle</code>), not be violated when the methods of type <code>S</code> (e.g. <code>Square</code>) are called instead.</p>\n\n<pre class="lang-scala prettyprint-override"><code>val rect : Rectangle = new Square(5) // thinks it\'s a Rectangle, but is a Square\nval rect2 : Rectangle = rect.setWidth(10) // height is 10, LSP violation\n</code></pre>\n\n<p>Even a type with <em>immutable fields</em> still has invariants, e.g. the <em>immutable</em> Rectangle setters expect dimensions to be independently modified, but the <em>immutable</em> Square setters violate this expectation.</p>\n\n<pre class="lang-scala prettyprint-override"><code>class Rectangle( val width : Int, val height : Int )\n{\n   def setWidth( w : Int ) = new Rectangle(w, height)\n   def setHeight( h : Int ) = new Rectangle(width, h)\n}\n\nclass Square( val side : Int ) extends Rectangle(side, side)\n{\n   override def setWidth( s : Int ) = new Square(s)\n   override def setHeight( s : Int ) = new Square(s)\n}\n</code></pre>\n\n<p>LSP requires that each method of the subtype <code>S</code> must have contravariant input parameter(s) and a covariant output.</p>\n\n<p>Contravariant means the variance is contrary to the direction of the inheritance, i.e. the type <code>Si</code>, of each input parameter of each method of the subtype <code>S</code>, must be the same or a <em>supertype</em> of the type <code>Ti</code> of the corresponding input parameter of the corresponding method of the supertype <code>T</code>.</p>\n\n<p>Covariance means the variance is in the same direction of the inheritance, i.e. the type <code>So</code>, of the output of each method of the subtype <code>S</code>, must be the same or a <em>subtype</em> of the type <code>To</code> of the corresponding output of the corresponding method of the supertype <code>T</code>.</p>\n\n<p>This is because if the caller thinks it has a type <code>T</code>, thinks it is calling a method of <code>T</code>, then it supplies argument(s) of type <code>Ti</code> and assigns the output to the type <code>To</code>. When it is actually calling the corresponding method of <code>S</code>, then each <code>Ti</code> input argument is assigned to a <code>Si</code> input parameter, and the <code>So</code> output is assigned to the type <code>To</code>. Thus if <code>Si</code> were not contravariant w.r.t. to <code>Ti</code>, then a subtype <code>Xi</code>—which would not be a subtype of <code>Si</code>—could be assigned to <code>Ti</code>.</p>\n\n<p>Additionally, for languages (e.g. Scala or Ceylon) which have definition-site variance annotations on type polymorphism parameters (i.e. generics), the co- or contra- direction of the variance annotation for each type parameter of the type <code>T</code> must be <a href="https://stackoverflow.com/q/5278591">opposite</a> or same direction respectively to every input parameter or output (of every method of <code>T</code>) that has the type of the type parameter.</p>\n\n<p>Additionally, for each input parameter or output that has a function type, the variance direction required is reversed. This rule is applied recursively.</p>\n\n<hr>\n\n<p><a href="https://stackoverflow.com/a/8352969">Subtyping is appropriate</a> where the invariants can be enumerated.</p>\n\n<p>There is much ongoing research on how to model invariants, so that they are enforced by the compiler.</p>\n\n<p><a href="http://www.cs.cmu.edu/~aldrich/papers/onward2009-state.pdf#page3" rel="nofollow noreferrer">Typestate</a> (see page 3) declares and enforces state invariants orthogonal to type. Alternatively, invariants can be enforced by <a href="http://lambda-the-ultimate.org/node/4009#comment-60775" rel="nofollow noreferrer">converting assertions to types</a>. For example, to assert that a file is open before closing it, then File.open() could return an OpenFile type, which contains a close() method that is not available in File. A <a href="http://blog.tmorris.net/scala-exercise-with-types-and-abstraction/" rel="nofollow noreferrer">tic-tac-toe API</a> can be another example of employing typing to enforce invariants at compile-time. The type system may even be Turing-complete, e.g. <a href="https://stackoverflow.com/a/4050833">Scala</a>. Dependently-typed languages and theorem provers formalize the models of higher-order typing. </p>\n\n<p>Because of the need for semantics to <a href="http://lambda-the-ultimate.org/node/4009#comment-60765" rel="nofollow noreferrer">abstract over extension</a>, I expect that employing typing to model invariants, i.e. unified higher-order denotational semantics, is superior to the Typestate. ‘Extension’ means the unbounded, permuted composition of uncoordinated, modular development. Because it seems to me to be the antithesis of unification and thus degrees-of-freedom, to have two mutually-dependent models (e.g. types and Typestate) for expressing the shared semantics, which can\'t be unified with each other for extensible composition. For example, <a href="http://en.wikipedia.org/wiki/Expression_problem" rel="nofollow noreferrer">Expression Problem</a>-like extension was unified in the subtyping, function overloading, and parametric typing domains.</p>\n\n<p>My theoretical position is that for <a href="http://www.coolpage.com/commentary/economic/shelby/Understand%20Everything%20Fundamentally.html" rel="nofollow noreferrer">knowledge to exist</a> (see section “Centralization is blind and unfit”), there will <em>never</em> be a general model that can enforce 100% coverage of all possible invariants in a Turing-complete computer language. For knowledge to exist, unexpected possibilities much exist, i.e. disorder and entropy must always be increasing. This is the entropic force. To prove all possible computations of a potential extension, is to compute a priori all possible extension.</p>\n\n<p>This is why the Halting Theorem exists, i.e. it is undecidable whether every possible program in a Turing-complete programming language terminates. It can be proven that some specific program terminates (one which all possibilities have been defined and computed). But it is impossible to prove that all possible extension of that program terminates, unless the possibilities for extension of that program is not Turing complete (e.g. via dependent-typing). Since the fundamental requirement for Turing-completeness is <a href="https://stackoverflow.com/q/8283566">unbounded recursion</a>, it is intuitive to understand how Gödel\'s incompleteness theorems and Russell\'s paradox apply to extension.</p>\n\n<p>An interpretation of these theorems incorporates them in a generalized conceptual understanding of the entropic force:</p>\n\n<ul>\n<li><strong>Gödel\'s incompleteness theorems</strong>: any formal theory, in which all arithmetic truths can be proved, is inconsistent.</li>\n<li><strong><a href="http://plato.stanford.edu/entries/russell-paradox/#SOTP" rel="nofollow noreferrer">Russell\'s paradox</a></strong>: every membership rule for a set that can contain a set, either enumerates the specific type of each member or contains itself. Thus sets either cannot be extended or they are unbounded recursion. For example, the set of everything that is not a teapot, includes itself, which includes itself, which includes itself, etc…. Thus a rule is inconsistent if it (may contain a set and) does not enumerate the specific types (i.e. allows all unspecified types) and does not allow unbounded extension. This is the set of sets that are not members of themselves. This inability to be both consistent and completely enumerated over all possible extension, is Gödel\'s incompleteness theorems.</li>\n<li><strong>Liskov Substition Principle</strong>: generally it is an undecidable problem whether any set is the subset of another, i.e. inheritance is generally undecidable.</li>\n<li><strong>Linsky Referencing</strong>: it is undecidable what the computation of something is, when it is described or perceived, i.e. perception (reality) has no absolute point of reference.</li>\n<li><strong>Coase\'s theorem</strong>: there is no external reference point, thus any barrier to unbounded external possibilities will fail.</li>\n<li><strong><a href="http://en.wikipedia.org/wiki/Second_law_of_thermodynamics#Mathematical_descriptions" rel="nofollow noreferrer">Second law of thermodynamics</a></strong>: the entire universe (a closed system, i.e. everything) trends to maximum disorder, i.e. maximum independent possibilities.</li>\n</ul>\n'}, {'answer_id': 15625091, 'author': 'avandeursen', 'author_id': 165292, 'author_profile': 'https://Stackoverflow.com/users/165292', 'pm_score': 4, 'selected': False, 'text': '<p>An important example of the <em>use</em> of LSP is in <strong>software testing</strong>.</p>\n\n<p>If I have a class A that is an LSP-compliant subclass of B, then I can reuse the test suite of B to test A.</p>\n\n<p>To fully test subclass A, I probably need to add a few more test cases, but at the minimum I can reuse all of superclass B\'s test cases. </p>\n\n<p>A way to realize is this by building what McGregor calls a "Parallel hierarchy for testing": My <code>ATest</code> class will inherit from <code>BTest</code>. Some form of injection is then needed to ensure the test case works with objects of type A rather than of type B (a simple template method pattern will do).</p>\n\n<p>Note that reusing the super-test suite for all subclass implementations is in fact a way to test that these subclass implementations are LSP-compliant. Thus, one can also argue that one <em>should</em> run the superclass test suite in the context of any subclass.</p>\n\n<p>See also the answer to the Stackoverflow question "<a href="https://stackoverflow.com/a/9367854/165292">Can I implement a series of reusable tests to test an interface\'s implementation?</a>"</p>\n'}, {'answer_id': 18693439, 'author': 'Ryszard Dżegan', 'author_id': 2042090, 'author_profile': 'https://Stackoverflow.com/users/2042090', 'pm_score': 2, 'selected': False, 'text': '<p>I encourage you to read the article: <a href="http://www.codeproject.com/Articles/648987/Violating-Liskov-Substitution-Principle-LSP" rel="nofollow">Violating Liskov Substitution Principle (LSP)</a>.</p>\n\n<p>You can find there an explanation what is the Liskov Substitution Principle, general clues helping you to guess if you have already violated it and an example of approach that will help you to make your class hierarchy be more safe.</p>\n'}, {'answer_id': 20795221, 'author': 'aknon', 'author_id': 2271385, 'author_profile': 'https://Stackoverflow.com/users/2271385', 'pm_score': 3, 'selected': False, 'text': '<p>Some addendum:<br/> I wonder why didn\'t anybody write about the Invariant , preconditions and post conditions of the base class that must be obeyed by the derived classes.\nFor a derived class D to be completely sustitutable by the Base class B, class D must obey certain conditions:</p>\n\n<ul>\n<li>In-variants of  base class must be preserved by the derived class</li>\n<li>Pre-conditions of the base class must not be strengthened by the derived class</li>\n<li>Post-conditions of the base class must not be weakened by the derived class.</li>\n</ul>\n\n<p>So the derived must be aware of the above three conditions imposed by the base class. Hence, the rules of subtyping are pre-decided. Which means, \'IS A\' relationship shall be obeyed only when certain rules are obeyed by the subtype. These rules, in the form of invariants, precoditions and postcondition, should be decided by a formal \'<a href="http://en.wikipedia.org/wiki/Design_by_contract" rel="noreferrer">design contract</a>\'.</p>\n\n<p>Further discussions on this available at my blog: <a href="http://design-principle-pattern.blogspot.in/2013/12/liskov-substitution-principle.html" rel="noreferrer">Liskov Substitution principle</a></p>\n'}, {'answer_id': 31664017, 'author': 'Wouter', 'author_id': 4491768, 'author_profile': 'https://Stackoverflow.com/users/4491768', 'pm_score': 3, 'selected': False, 'text': '<p>A square is a rectangle where the width equals the height. If the square sets two different sizes for the width and height it violates the square invariant. This is worked around by introducing side effects. But if the rectangle had a setSize(height, width) with precondition 0 &lt; height and 0 &lt; width. The derived subtype method requires height == width; a stronger precondition (and that violates lsp). This shows that though square is a rectangle it is not a valid subtype because the precondition is strengthened. The work around (in general a bad thing) cause a side effect and this weakens the post condition (which violates lsp). setWidth on the base has post condition 0 &lt; width. The derived weakens it with height == width.</p>\n\n<p>Therefore a resizable square is not a resizable rectangle.</p>\n'}, {'answer_id': 37012893, 'author': 'Prasa', 'author_id': 4573646, 'author_profile': 'https://Stackoverflow.com/users/4573646', 'pm_score': 2, 'selected': False, 'text': '<p>The clearest explanation for LSP I found so far has been "The Liskov Substitution Principle says that the object of a derived class should be able to replace an object of the base class without bringing any errors in the system or modifying the behavior of the base class" from <a href="http://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/06/30/simplifying-the-liskov-substitution-principle-of-solid-in-c.aspx" rel="nofollow">here</a>. The article gives code example for violating LSP and fixing it.</p>\n'}, {'answer_id': 38923313, 'author': 'Raghu Reddy Muttana', 'author_id': 4008404, 'author_profile': 'https://Stackoverflow.com/users/4008404', 'pm_score': 2, 'selected': False, 'text': '<p>LISKOV SUBSTITUTION PRINCIPLE (From Mark Seemann book) states that we should be able to replace one implementation of an interface with another without breaking either client or implementation.It’s this principle that enables to address requirements that         occur in the future, even if we can’t foresee them today.</p>\n\n<p>If we unplug the computer from the wall (Implementation), neither the wall outlet (Interface) nor the computer (Client) breaks down (in fact, if it’s a laptop computer, it can even run on its batteries for a period of time). With software, however, a client often expects a service to be available.         If the service was removed, we get a NullReferenceException. To deal with this type of situation, we can create an implementation of an interface that does “nothing.” This is a design pattern known as Null Object,[4] and it corresponds roughly to unplugging the computer from the wall. Because we’re using loose coupling, we can replace a real implementation with something that does         nothing without causing trouble.</p>\n'}, {'answer_id': 38933690, 'author': 'Cù Đức Hiếu', 'author_id': 2827960, 'author_profile': 'https://Stackoverflow.com/users/2827960', 'pm_score': 5, 'selected': False, 'text': "<p>There is a checklist to determine whether or not you are violating Liskov.</p>\n<ul>\n<li>If you violate one of the following items -&gt; you violate Liskov.</li>\n<li>If you don't violate any -&gt; can't conclude anything.</li>\n</ul>\n<p>Check list:</p>\n<ul>\n<li><p><strong>No new exceptions should be thrown in derived class</strong>: If your base class threw ArgumentNullException then your sub classes were only allowed to throw exceptions of type ArgumentNullException or any exceptions derived from ArgumentNullException. Throwing IndexOutOfRangeException is a violation of Liskov.</p>\n</li>\n<li><p><strong>Pre-conditions cannot be strengthened</strong>: Assume your base class works with a member int. Now your sub-type requires that int to be positive. This is strengthened pre-conditions, and now any code that worked perfectly fine before with negative ints is broken.</p>\n</li>\n<li><p><strong>Post-conditions cannot be weakened</strong>: Assume your base class required all connections to the database should be closed before the method returned. In your sub-class you overrode that method and left the connection open for further reuse. You have weakened the post-conditions of that method.</p>\n</li>\n<li><p><strong>Invariants must be preserved</strong>: The most difficult and painful constraint to fulfill. Invariants are sometimes hidden in the base class and the only way to reveal them is to read the code of the base class. Basically you have to be sure when you override a method anything unchangeable must remain unchanged after your overridden method is executed. The best thing I can think of is to enforce these invariant constraints in the base class but that would not be easy.</p>\n</li>\n<li><p><strong>History Constraint</strong>: When overriding a method you are not allowed to modify an unmodifiable property in the base class. Take a look at these code and you can see Name is defined to be unmodifiable (private set) but SubType introduces new method that allows modifying it (through reflection):</p>\n<pre><code> public class SuperType\n {\n     public string Name { get; private set; }\n     public SuperType(string name, int age)\n     {\n         Name = name;\n         Age = age;\n     }\n }\n public class SubType : SuperType\n {\n     public void ChangeName(string newName)\n     {\n         var propertyType = base.GetType().GetProperty(&quot;Name&quot;).SetValue(this, newName);\n     }\n }\n</code></pre>\n</li>\n</ul>\n<p>There are 2 others items: <strong>Contravariance of method arguments</strong> and <strong>Covariance of return types</strong>. But it is not possible in C# (I'm a C# developer) so I don't care about them.</p>\n"}, {'answer_id': 41210681, 'author': 'snagpaul', 'author_id': 7119946, 'author_profile': 'https://Stackoverflow.com/users/7119946', 'pm_score': 5, 'selected': False, 'text': "<p>I guess everyone kind of covered what LSP is technically: You basically want to be able to abstract away from subtype details and use supertypes safely. </p>\n\n<p>So Liskov has 3 underlying rules: </p>\n\n<ol>\n<li><p>Signature Rule : There should be a valid implementation of every operation of the supertype in the subtype syntactically. Something a compiler will be able to check for you. There is a little rule about throwing fewer exceptions and being at least as accessible as the supertype methods. </p></li>\n<li><p>Methods Rule: The implementation of those operations is semantically sound.</p>\n\n<ul>\n<li>Weaker Preconditions : The subtype functions should take at least what the supertype took as input, if not more. </li>\n<li>Stronger Postconditions: They should produce a subset of the output the supertype methods produced.    </li>\n</ul></li>\n<li><p>Properties Rule : This goes beyond individual function calls. </p>\n\n<ul>\n<li>Invariants : Things that are always true must remain true. Eg. a Set's size is never negative. </li>\n<li>Evolutionary Properties : Usually something to do with immutability or the kind of states the object can be in. Or maybe the object only grows and never shrinks so the subtype methods shouldn't make it. </li>\n</ul></li>\n</ol>\n\n<p>All these properties need to be preserved and the extra subtype functionality shouldn't violate supertype properties. </p>\n\n<p>If these three things are taken care of , you have abstracted away from the underlying stuff and you are writing loosely coupled code. </p>\n\n<p>Source: Program Development in Java - Barbara Liskov </p>\n"}, {'answer_id': 44913313, 'author': 'maysara', 'author_id': 5503714, 'author_profile': 'https://Stackoverflow.com/users/5503714', 'pm_score': 9, 'selected': False, 'text': "<blockquote>\n<p>Substitutability is a principle in object-oriented programming stating that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S</p>\n</blockquote>\n<p>Let's do a simple example in Java:</p>\n<h2>Bad example</h2>\n<pre><code>public class Bird{\n    public void fly(){}\n}\npublic class Duck extends Bird{}\n</code></pre>\n<p>The duck can fly because it is a bird, but what about this:</p>\n<pre><code>public class Ostrich extends Bird{}\n</code></pre>\n<p>Ostrich is a bird, but it can't fly, Ostrich class is a subtype of class Bird, but it shouldn't be able to use the fly method, that means we are breaking the LSP principle.</p>\n<h2>Good example</h2>\n<pre><code>public class Bird{}\npublic class FlyingBirds extends Bird{\n    public void fly(){}\n}\npublic class Duck extends FlyingBirds{}\npublic class Ostrich extends Bird{} \n</code></pre>\n"}, {'answer_id': 45708888, 'author': 'Alireza Rahmani khalili', 'author_id': 2043248, 'author_profile': 'https://Stackoverflow.com/users/2043248', 'pm_score': 3, 'selected': False, 'text': "<p>In a very simple sentence, we can say:</p>\n\n<p>The child class must not violate its base class characteristics. It must be capable with it. We can say it's same as subtyping.</p>\n"}, {'answer_id': 46383470, 'author': 'Ishan Aggarwal', 'author_id': 8662033, 'author_profile': 'https://Stackoverflow.com/users/8662033', 'pm_score': 2, 'selected': False, 'text': "<p>Likov's Substitution Principle states that <em>if a program module is using a Base class, then the reference to the Base class can be replaced with a Derived class without affecting the functionality of the program module.</em></p>\n\n<p>Intent - Derived types must be completely substitute able for their base types.</p>\n\n<p>Example - Co-variant return types in java.</p>\n"}, {'answer_id': 46638860, 'author': 'inf3rno', 'author_id': 607033, 'author_profile': 'https://Stackoverflow.com/users/607033', 'pm_score': 2, 'selected': False, 'text': '<p>Let\'s say we use a rectangle in our code</p>\n\n<pre><code>r = new Rectangle();\n// ...\nr.setDimensions(1,2);\nr.fill(colors.red());\ncanvas.draw(r);\n</code></pre>\n\n<p>In our geometry class we learned that a square is a special type of rectangle because its width is the same length as its height. Let\'s make a <code>Square</code> class as well based on this info:</p>\n\n<pre><code>class Square extends Rectangle {\n    setDimensions(width, height){\n        assert(width == height);\n        super.setDimensions(width, height);\n    }\n} \n</code></pre>\n\n<p>If we replace the <code>Rectangle</code> with <code>Square</code> in our first code, then it will break:</p>\n\n<pre><code>r = new Square();\n// ...\nr.setDimensions(1,2); // assertion width == height failed\nr.fill(colors.red());\ncanvas.draw(r);\n</code></pre>\n\n<p>This is because the <code>Square</code> has a new precondition we did not have in the <code>Rectangle</code> class: <code>width == height</code>. According to LSP the <code>Rectangle</code> instances should be substitutable with <code>Rectangle</code> subclass instances. This is because these instances pass the type check for <code>Rectangle</code> instances and so they will cause unexpected errors in your code.</p>\n\n<p>This was an example for the <em>"preconditions cannot be strengthened in a subtype"</em> part in the <a href="https://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="nofollow noreferrer">wiki article</a>. So to sum up, violating LSP will probably cause errors in your code at some point.</p>\n'}, {'answer_id': 46995392, 'author': 'Lukas Lukac', 'author_id': 1162217, 'author_profile': 'https://Stackoverflow.com/users/1162217', 'pm_score': 5, 'selected': False, 'text': '<p><strong>Long</strong> story short, let\'s leave rectangles rectangles and squares squares, practical example when extending a parent class, you have to either PRESERVE the exact parent API or to EXTEND IT.</p>\n\n<p>Let\'s say you have a <strong>base</strong> ItemsRepository.</p>\n\n\n\n<pre class="lang-php prettyprint-override"><code>class ItemsRepository\n{\n    /**\n    * @return int Returns number of deleted rows\n    */\n    public function delete()\n    {\n        // perform a delete query\n        $numberOfDeletedRows = 10;\n\n        return $numberOfDeletedRows;\n    }\n}\n</code></pre>\n\n<p>And a sub class extending it:</p>\n\n<pre class="lang-php prettyprint-override"><code>class BadlyExtendedItemsRepository extends ItemsRepository\n{\n    /**\n     * @return void Was suppose to return an INT like parent, but did not, breaks LSP\n     */\n    public function delete()\n    {\n        // perform a delete query\n        $numberOfDeletedRows = 10;\n\n        // we broke the behaviour of the parent class\n        return;\n    }\n}\n</code></pre>\n\n<p>Then you could have a <strong>Client</strong> working with the Base ItemsRepository API and relying on it.</p>\n\n<pre class="lang-php prettyprint-override"><code>/**\n * Class ItemsService is a client for public ItemsRepository "API" (the public delete method).\n *\n * Technically, I am able to pass into a constructor a sub-class of the ItemsRepository\n * but if the sub-class won\'t abide the base class API, the client will get broken.\n */\nclass ItemsService\n{\n    /**\n     * @var ItemsRepository\n     */\n    private $itemsRepository;\n\n    /**\n     * @param ItemsRepository $itemsRepository\n     */\n    public function __construct(ItemsRepository $itemsRepository)\n    {\n        $this-&gt;itemsRepository = $itemsRepository;\n    }\n\n    /**\n     * !!! Notice how this is suppose to return an int. My clients expect it based on the\n     * ItemsRepository API in the constructor !!!\n     *\n     * @return int\n     */\n    public function delete()\n    {\n        return $this-&gt;itemsRepository-&gt;delete();\n    }\n} \n</code></pre>\n\n<p>The <strong>LSP</strong> is broken when <strong>substituting</strong> <strong>parent</strong> class with a <strong>sub class breaks the API\'s contract</strong>.</p>\n\n<pre class="lang-php prettyprint-override"><code>class ItemsController\n{\n    /**\n     * Valid delete action when using the base class.\n     */\n    public function validDeleteAction()\n    {\n        $itemsService = new ItemsService(new ItemsRepository());\n        $numberOfDeletedItems = $itemsService-&gt;delete();\n\n        // $numberOfDeletedItems is an INT :)\n    }\n\n    /**\n     * Invalid delete action when using a subclass.\n     */\n    public function brokenDeleteAction()\n    {\n        $itemsService = new ItemsService(new BadlyExtendedItemsRepository());\n        $numberOfDeletedItems = $itemsService-&gt;delete();\n\n        // $numberOfDeletedItems is a NULL :(\n    }\n}\n</code></pre>\n\n<p>You can learn more about writing maintainable software in my course: <a href="https://www.udemy.com/enterprise-php/" rel="noreferrer">https://www.udemy.com/enterprise-php/</a></p>\n'}, {'answer_id': 48855491, 'author': 'Steve Chamaillard', 'author_id': 3887300, 'author_profile': 'https://Stackoverflow.com/users/3887300', 'pm_score': 5, 'selected': False, 'text': '<p>I see rectangles and squares in every answer, and how to violate the LSP.</p>\n\n<p>I\'d like to show how the LSP can be conformed to with a real-world example :</p>\n\n\n\n<pre class="lang-php prettyprint-override"><code>&lt;?php\n\ninterface Database \n{\n    public function selectQuery(string $sql): array;\n}\n\nclass SQLiteDatabase implements Database\n{\n    public function selectQuery(string $sql): array\n    {\n        // sqlite specific code\n\n        return $result;\n    }\n}\n\nclass MySQLDatabase implements Database\n{\n    public function selectQuery(string $sql): array\n    {\n        // mysql specific code\n\n        return $result; \n    }\n}\n</code></pre>\n\n<p>This design conforms to the LSP because the behaviour remains unchanged regardless of the implementation we choose to use.</p>\n\n<p>And yes, you can violate LSP in this configuration doing one simple change like so :</p>\n\n<pre class="lang-php prettyprint-override"><code>&lt;?php\n\ninterface Database \n{\n    public function selectQuery(string $sql): array;\n}\n\nclass SQLiteDatabase implements Database\n{\n    public function selectQuery(string $sql): array\n    {\n        // sqlite specific code\n\n        return $result;\n    }\n}\n\nclass MySQLDatabase implements Database\n{\n    public function selectQuery(string $sql): array\n    {\n        // mysql specific code\n\n        return [\'result\' =&gt; $result]; // This violates LSP !\n    }\n}\n</code></pre>\n\n<p>Now the subtypes cannot be used the same way since they don\'t produce the same result anymore.</p>\n'}, {'answer_id': 50445304, 'author': 'GauRang Omar', 'author_id': 6653785, 'author_profile': 'https://Stackoverflow.com/users/6653785', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n  <p><strong>Liskov\'s Substitution Principle(LSP)</strong></p>\n  \n  <p>All the time we design a program module and we create some class\n  hierarchies. Then we extend some classes creating some derived\n  classes.</p>\n  \n  <p>We must make sure that the new derived classes just extend without\n  replacing the functionality of old classes. Otherwise, the new classes\n  can produce undesired effects when they are used in existing program\n  modules.</p>\n  \n  <p>Liskov\'s Substitution Principle states that if a program module is\n  using a Base class, then the reference to the Base class can be\n  replaced with a Derived class without affecting the functionality of\n  the program module.</p>\n</blockquote>\n\n<p><strong>Example:</strong></p>\n\n<p>Below is the classic example for which the Liskov\'s Substitution Principle is violated. In the example, 2 classes are used: Rectangle and Square. Let\'s assume that the Rectangle object is used somewhere in the application. We extend the application and add the Square class. The square class is returned by a factory pattern, based on some conditions and we don\'t know the exact what type of object will be returned. But we know it\'s a Rectangle. We get the rectangle object, set the width to 5 and height to 10 and get the area. For a rectangle with width 5 and height 10, the area should be 50. Instead, the result will be 100</p>\n\n<pre><code>    // Violation of Likov\'s Substitution Principle\nclass Rectangle {\n    protected int m_width;\n    protected int m_height;\n\n    public void setWidth(int width) {\n        m_width = width;\n    }\n\n    public void setHeight(int height) {\n        m_height = height;\n    }\n\n    public int getWidth() {\n        return m_width;\n    }\n\n    public int getHeight() {\n        return m_height;\n    }\n\n    public int getArea() {\n        return m_width * m_height;\n    }\n}\n\nclass Square extends Rectangle {\n    public void setWidth(int width) {\n        m_width = width;\n        m_height = width;\n    }\n\n    public void setHeight(int height) {\n        m_width = height;\n        m_height = height;\n    }\n\n}\n\nclass LspTest {\n    private static Rectangle getNewRectangle() {\n        // it can be an object returned by some factory ...\n        return new Square();\n    }\n\n    public static void main(String args[]) {\n        Rectangle r = LspTest.getNewRectangle();\n\n        r.setWidth(5);\n        r.setHeight(10);\n        // user knows that r it\'s a rectangle.\n        // It assumes that he\'s able to set the width and height as for the base\n        // class\n\n        System.out.println(r.getArea());\n        // now he\'s surprised to see that the area is 100 instead of 50.\n    }\n}\n</code></pre>\n\n<blockquote>\n  <p><strong>Conclusion:</strong></p>\n  \n  <p>This principle is just an extension of the Open Close Principle and it\n  means that we must make sure that new derived classes are extending\n  the base classes without changing their behavior.</p>\n</blockquote>\n\n<p>See also: <strong><a href="https://en.wikipedia.org/wiki/Open/closed_principle" rel="noreferrer">Open Close Principle</a></strong> </p>\n\n<p>Some similar concepts for better structure: <a href="https://en.wikipedia.org/wiki/Convention_over_configuration" rel="noreferrer">Convention over configuration</a></p>\n'}, {'answer_id': 51811062, 'author': 'Vadim Samokhin', 'author_id': 618020, 'author_profile': 'https://Stackoverflow.com/users/618020', 'pm_score': 2, 'selected': False, 'text': '<p>Here is an excerpt from <a href="https://dzone.com/articles/liskov-substitution-principle-or-how-to-create-bea" rel="nofollow noreferrer">this post</a> that clarifies things nicely:</p>\n\n<p>[..] in order to comprehend some principles, it’s important to realize when it’s been violated. This is what I will do now.</p>\n\n<p>What does the violation of this principle mean? It implies that an object doesn’t fulfill the contract imposed by an abstraction expressed with an interface. In other words, it means that you identified your abstractions wrong.</p>\n\n<p>Consider the following example:</p>\n\n<pre><code>interface Account\n{\n    /**\n     * Withdraw $money amount from this account.\n     *\n     * @param Money $money\n     * @return mixed\n     */\n    public function withdraw(Money $money);\n}\nclass DefaultAccount implements Account\n{\n    private $balance;\n    public function withdraw(Money $money)\n    {\n        if (!$this-&gt;enoughMoney($money)) {\n            return;\n        }\n        $this-&gt;balance-&gt;subtract($money);\n    }\n}\n</code></pre>\n\n<p>Is this a violation of LSP? Yes. This is because the account’s contract tells us that an account would be withdrawn, but this is not always the case. So, what should I do in order to fix it? I just modify the contract:</p>\n\n<pre><code>interface Account\n{\n    /**\n     * Withdraw $money amount from this account if its balance is enough.\n     * Otherwise do nothing.\n     *\n     * @param Money $money\n     * @return mixed\n     */\n    public function withdraw(Money $money);\n}\n</code></pre>\n\n<p>Voilà, now the contract is satisfied.</p>\n\n<p>This subtle violation often imposes a client with the ability to tell the difference between concrete objects employed. For example, given the first Account’s contract, it could look like the following:</p>\n\n<pre><code>class Client\n{\n    public function go(Account $account, Money $money)\n    {\n        if ($account instanceof DefaultAccount &amp;&amp; !$account-&gt;hasEnoughMoney($money)) {\n            return;\n        }\n        $account-&gt;withdraw($money);\n    }\n}\n</code></pre>\n\n<p>And, this automatically violates the open-closed principle [that is, for money withdrawal requirement. Because you never know what happens if an object violating the contract doesn\'t have enough money. Probably it just returns nothing, probably an exception will be thrown. So you have to check if it <code>hasEnoughMoney()</code> -- which is not part of an interface. So this forced concrete-class-dependent check is an OCP violation].</p>\n\n<p>This point also addresses a misconception that I encounter quite often about LSP violation. It says the “if a parent’s behavior changed in a child, then, it violates LSP.” However, it doesn’t — as long as a child doesn’t violate its parent’s contract.</p>\n'}, {'answer_id': 54615672, 'author': 'Khaled Qasem', 'author_id': 8550140, 'author_profile': 'https://Stackoverflow.com/users/8550140', 'pm_score': 5, 'selected': False, 'text': '<p>Let’s illustrate in Java:</p>\n\n<pre><code>class TrasportationDevice\n{\n   String name;\n   String getName() { ... }\n   void setName(String n) { ... }\n\n   double speed;\n   double getSpeed() { ... }\n   void setSpeed(double d) { ... }\n\n   Engine engine;\n   Engine getEngine() { ... }\n   void setEngine(Engine e) { ... }\n\n   void startEngine() { ... }\n}\n\nclass Car extends TransportationDevice\n{\n   @Override\n   void startEngine() { ... }\n}\n</code></pre>\n\n<p>There is no problem here, right? A car is definitely a transportation device, and here we can see that it overrides the startEngine()  method of its superclass.</p>\n\n<p>Let’s add another transportation device:</p>\n\n<pre><code>class Bicycle extends TransportationDevice\n{\n   @Override\n   void startEngine() /*problem!*/\n}\n</code></pre>\n\n<p>Everything isn’t going as planned now! Yes, a bicycle is a transportation device, however, it does not have an engine and hence, the method startEngine() cannot be implemented.</p>\n\n<blockquote>\n  <p>These are the kinds of problems that violation of Liskov Substitution\n  Principle leads to, and they can most usually be recognized by a\n  method that does nothing, or even can’t be implemented.</p>\n</blockquote>\n\n<p>The solution to these problems is a correct inheritance hierarchy, and in our case we would solve the problem by differentiating classes of transportation devices with and without engines. Even though a bicycle is a transportation device, it doesn’t have an engine. In this example our definition of transportation device is wrong. It should not have an engine.</p>\n\n<p>We can refactor our TransportationDevice  class as follows:</p>\n\n<pre><code>class TrasportationDevice\n{\n   String name;\n   String getName() { ... }\n   void setName(String n) { ... }\n\n   double speed;\n   double getSpeed() { ... }\n   void setSpeed(double d) { ... }\n}\n</code></pre>\n\n<p>Now we can extend TransportationDevice  for non-motorized devices.</p>\n\n<pre><code>class DevicesWithoutEngines extends TransportationDevice\n{  \n   void startMoving() { ... }\n}\n</code></pre>\n\n<p>And extend TransportationDevice  for motorized devices. Here is is more appropriate to add the Engine  object.</p>\n\n<pre><code>class DevicesWithEngines extends TransportationDevice\n{  \n   Engine engine;\n   Engine getEngine() { ... }\n   void setEngine(Engine e) { ... }\n\n   void startEngine() { ... }\n}\n</code></pre>\n\n<p>Thus our Car  class becomes more specialized, while adhering to the Liskov Substitution Principle.</p>\n\n<pre><code>class Car extends DevicesWithEngines\n{\n   @Override\n   void startEngine() { ... }\n}\n</code></pre>\n\n<p>And our Bicycle  class is also in compliance with the Liskov Substitution Principle.</p>\n\n<pre><code>class Bicycle extends DevicesWithoutEngines\n{\n   @Override\n   void startMoving() { ... }\n}\n</code></pre>\n'}, {'answer_id': 55549272, 'author': 'Zahra.HY', 'author_id': 5723268, 'author_profile': 'https://Stackoverflow.com/users/5723268', 'pm_score': 2, 'selected': False, 'text': "<p>LSP says that ''Objects should be replaceable by their subtypes''.\nOn the other hand, this principle points to </p>\n\n<blockquote>\n  <p>Child classes should never break the parent class`s type definitions.</p>\n</blockquote>\n\n<p>and the following example helps to have a better understanding of LSP.</p>\n\n<p>Without LSP:</p>\n\n<pre><code>public interface CustomerLayout{\n\n    public void render();\n}\n\n\npublic FreeCustomer implements CustomerLayout {\n     ...\n    @Override\n    public void render(){\n        //code\n    }\n}\n\n\npublic PremiumCustomer implements CustomerLayout{\n    ...\n    @Override\n    public void render(){\n        if(!hasSeenAd)\n            return; //it isn`t rendered in this case\n        //code\n    }\n}\n\npublic void renderView(CustomerLayout layout){\n    layout.render();\n}\n</code></pre>\n\n<p>Fixing by LSP:</p>\n\n<pre><code>public interface CustomerLayout{\n    public void render();\n}\n\n\npublic FreeCustomer implements CustomerLayout {\n     ...\n    @Override\n    public void render(){\n        //code\n    }\n}\n\n\npublic PremiumCustomer implements CustomerLayout{\n    ...\n    @Override\n    public void render(){\n        if(!hasSeenAd)\n            showAd();//it has a specific behavior based on its requirement\n        //code\n    }\n}\n\npublic void renderView(CustomerLayout layout){\n    layout.render();\n}\n</code></pre>\n"}, {'answer_id': 55862359, 'author': 'prady00', 'author_id': 1138654, 'author_profile': 'https://Stackoverflow.com/users/1138654', 'pm_score': 0, 'selected': False, 'text': '<p>Let me try, consider an interface: </p>\n\n<pre><code>interface Planet{\n}\n</code></pre>\n\n<p>This is implemented by class:</p>\n\n<pre><code>class Earth implements Planet {\n    public $radius;\n    public function construct($radius) {\n        $this-&gt;radius = $radius;\n    }\n}\n</code></pre>\n\n<p>You will use Earth as:</p>\n\n<pre><code>$planet = new Earth(6371);\n$calc = new SurfaceAreaCalculator($planet);\n$calc-&gt;output();\n</code></pre>\n\n<p>Now consider one more class which extends Earth:</p>\n\n<pre><code>class LiveablePlanet extends Earth{\n   public function color(){\n   }\n}\n</code></pre>\n\n<p>Now according to LSP, you should be able to use LiveablePlanet in place of Earth and it should not break your system. Like:</p>\n\n<pre><code>$planet = new LiveablePlanet(6371);  // Earlier we were using Earth here\n$calc = new SurfaceAreaCalculator($planet);\n$calc-&gt;output();\n</code></pre>\n\n<p>Examples taken from <a href="https://bootsity.com/php/understanding-the-solid-principles-of-software-engineering" rel="nofollow noreferrer">here</a></p>\n'}, {'answer_id': 57556229, 'author': 'Rahamath', 'author_id': 6537273, 'author_profile': 'https://Stackoverflow.com/users/6537273', 'pm_score': 4, 'selected': False, 'text': '<p><strong>The Liskov Substitution Principle</strong></p>\n\n<ul>\n<li>The overridden method shouldn’t remain empty</li>\n<li>The overridden method shouldn’t throw an error</li>\n<li>Base class or interface behavior should not go for modification (rework) as because of derived class behaviors.</li>\n</ul>\n'}, {'answer_id': 59896294, 'author': 'johannesMatevosyan', 'author_id': 3578809, 'author_profile': 'https://Stackoverflow.com/users/3578809', 'pm_score': 4, 'selected': False, 'text': '<p><a href="https://dev.to/erikwhiting88/liskov-substitution-principle-in-3-minutes-2dc6" rel="noreferrer">The LSP in simple terms</a> states that objects of the same superclass should be able to be <strong>swapped</strong> with each other without breaking anything.</p>\n\n<p>For example, if we have a <code>Cat</code> and a <code>Dog</code> class derived from an <code>Animal</code> class, any functions using the Animal class should be able to use <code>Cat</code> or <code>Dog</code> and behave normally.</p>\n'}, {'answer_id': 60494181, 'author': 'Ivan Porta', 'author_id': 6613232, 'author_profile': 'https://Stackoverflow.com/users/6613232', 'pm_score': 3, 'selected': False, 'text': "<p>This principle was introduced by <strong>Barbara Liskov</strong> in 1987 and extends the Open-Closed Principle by focusing on the behavior of a superclass and its subtypes. </p>\n\n<p>Its importance becomes obvious when we consider the consequences of violating it. Consider an application that uses the following class.</p>\n\n<pre><code>public class Rectangle \n{ \n  private double width;\n\n  private double height; \n\n  public double Width \n  { \n    get \n    { \n      return width; \n    } \n    set \n    { \n      width = value; \n    }\n  } \n\n  public double Height \n  { \n    get \n    { \n      return height; \n    } \n    set \n    { \n      height = value; \n    } \n  } \n}\n</code></pre>\n\n<p>Imagine that one day, the client demands the ability to manipulate squares in addition to rectangles. Since a square is a rectangle, the square class should be derived from the Rectangle class. </p>\n\n<pre><code>public class Square : Rectangle\n{\n} \n</code></pre>\n\n<p>However, by doing that we will encounter two problems:</p>\n\n<p>A square does not need both height and width variables inherited from the rectangle and this could create a significant waste in memory if we have to create hundreds of thousands of square objects.\nThe width and height setter properties inherited from the rectangle are inappropriate for a square since the width and height of a square are identical.\nIn order to set both height and width to the same value, we can create two new properties as follows:</p>\n\n<pre><code>public class Square : Rectangle\n{\n  public double SetWidth \n  { \n    set \n    { \n      base.Width = value; \n      base.Height = value; \n    } \n  } \n\n  public double SetHeight \n  { \n    set \n    { \n      base.Height = value; \n      base.Width = value; \n    } \n  } \n}\n</code></pre>\n\n<p>Now, when someone will set the width of a square object, its height will change accordingly and vice-versa.</p>\n\n<pre><code>Square s = new Square(); \ns.SetWidth(1); // Sets width and height to 1. \ns.SetHeight(2); // sets width and height to 2. \n</code></pre>\n\n<p>Let's move forward and consider this other function:</p>\n\n<pre><code>public void A(Rectangle r) \n{ \n  r.SetWidth(32); // calls Rectangle.SetWidth \n} \n</code></pre>\n\n<p>If we pass a reference to a square object into this function, we would violate the LSP because the function does not work for derivatives of its arguments. The properties width and height aren't polymorphic because they aren't declared virtual in rectangle (the square object will be corrupted because the height won't be changed).</p>\n\n<p>However, by declaring the setter properties to be virtual we will face another violation, the OCP. In fact, the creation of a derived class square is causing changes to the base class rectangle.</p>\n"}, {'answer_id': 64789005, 'author': 'yoAlex5', 'author_id': 4770877, 'author_profile': 'https://Stackoverflow.com/users/4770877', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Liskov Substitution Principle</strong></p>\n<p><a href="https://stackoverflow.com/a/66087638/4770877">[SOLID]</a></p>\n<p><strong>Inheritance</strong> Subtyping</p>\n<p><a href="https://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="nofollow noreferrer">Wiki Liskov substitution principle (LSP)</a></p>\n<blockquote>\n<p>Preconditions cannot be strengthened in a subtype.<br/>\nPostconditions cannot be weakened in a subtype.<br/>\nInvariants of the supertype must be preserved in a subtype.</p>\n</blockquote>\n<ul>\n<li>Subtype should not require(Preconditions) from caller more than supertype</li>\n<li>Subtype should not expose(Postconditions) for caller less than supertype</li>\n</ul>\n<p>*Precondition + Postcondition = <code>function (method) types</code><sup><a href="https://stackoverflow.com/a/60988242/4770877">[Swift Function type. Swift function vs method]</sup></a></p>\n<pre><code>//Swift function\nfunc foo(parameter: Class1) -&gt; Class2\n\n//function type\n(Class1) -&gt; Class2\n\n//Precondition\nClass1\n\n//Postcondition\nClass2\n</code></pre>\n<p>Example</p>\n<pre><code>//C3 -&gt; C2 -&gt; C1\n\nclass C1 {}\nclass C2: C1 {}\nclass C3: C2 {}\n</code></pre>\n<ul>\n<li><p>Preconditions(e.g. function <code>parameter type</code>) can be the same or <strong>weaker</strong>(strives for -&gt; C1)</p>\n</li>\n<li><p>Postconditions(e.g. function <code>returned type</code>) can be the same or <strong>stronger</strong>(strives for -&gt; C3)</p>\n</li>\n<li><p>Invariant variable<a href="https://stackoverflow.com/a/64788342/4770877"><sup>[About]</sup></a> of super type should stay invariant</p>\n</li>\n</ul>\n<p>Swift</p>\n<pre><code>class A {\n    func foo(a: C2) -&gt; C2 {\n        return C2()\n    }\n}\n\nclass B: A {\n    override func foo(a: C1) -&gt; C3 {\n        return C3()\n    }\n}\n</code></pre>\n<p>Java</p>\n<pre><code>class A {\n    public C2 foo(C2 a) {\n        return new C2();\n    }\n}\n\nclass B extends A {\n    @Override\n    public C3 foo(C2 a) { //You are available pass only C2 as parameter\n        return new C3();\n    }\n}\n</code></pre>\n<p><strong>Behavioral subtyping</strong></p>\n<p><a href="https://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="nofollow noreferrer">Wiki Liskov substitution principle (LSP)</a></p>\n<blockquote>\n<p>Contravariance of method parameter types in the subtype. <br/> Covariance of method return types in the subtype. <br/>\nNew exceptions cannot be thrown by the methods in the subtype, except if they are subtypes of exceptions thrown by the methods of the supertype.</p>\n</blockquote>\n<p><a href="https://stackoverflow.com/a/62752867/4770877">[Variance, Covariance, Contravariance, Invariance]</a></p>\n'}, {'answer_id': 64950848, 'author': 'Sarmad Sohail', 'author_id': 12785637, 'author_profile': 'https://Stackoverflow.com/users/12785637', 'pm_score': 3, 'selected': False, 'text': "<p>It states that if C is a subtype of E then E can be replaced with objects of type C without changing or breaking the behavior of the program. In simple words, derived classes should be substitutable for their parent classes. For example, if a <strong>Farmer’s son</strong> is Farmer then he can work in place of his father but if a <strong>Farmer’s son</strong> is a cricketer then he can’t work in place of his father.</p>\n<h3>Violation Example:</h3>\n<pre><code>public class Plane{\n\n  public void startEngine(){}      \n\n}        \npublic class FighterJet extends Plane{}\n    \npublic class PaperPlane extends Plane{}\n</code></pre>\n<p>In the given example <code>FighterPlane</code> and <code>PaperPlane</code> classes both extending the <code>Plane</code> class which contain <code>startEngine()</code> method. So it's clear that <code>FighterPlane</code> can start engine but <code>PaperPlane</code> can’t so it’s breaking <code>LSP</code>.</p>\n<p><code>PaperPlane</code> class although extending <code>Plane</code> class and should be substitutable in place of it but is not an eligible entity that Plane’s instance could be replaced by, because a paper plane can’t start the engine as it doesn’t have one. So the good example would be,</p>\n<h3>Respected Example:</h3>\n<pre><code>public class Plane{ \n} \npublic class RealPlane{\n\n  public void startEngine(){} \n\n}\npublic class FighterJet extends RealPlane{} \npublic class PaperPlane extends Plane{}\n</code></pre>\n"}, {'answer_id': 69253204, 'author': 'jferard', 'author_id': 6914441, 'author_profile': 'https://Stackoverflow.com/users/6914441', 'pm_score': 3, 'selected': False, 'text': "<p>The big picture :</p>\n<ul>\n<li>What is Liskov Substitution Principle about ? It's about what is (and what is not) a <strong>subtype</strong> of a given type.</li>\n<li>Why is it so important ? Because there is a difference between a <strong>subtype</strong> and a <strong>subclass</strong>.</li>\n</ul>\n<h1>Example</h1>\n<p>Unlike the other answers, I won't start with a Liskov Substitution Principle (LSP) violation, but with a LSP compliance. I use Java but it would be almost the same in every OOP language.</p>\n<h2><code>Circle</code> and <code>ColoredCircle</code></h2>\n<p>Geometrical examples seem pretty popular here.</p>\n<pre><code>class Circle {\n    private int radius;\n\n    public Circle(int radius) {\n        if (radius &lt; 0) {\n            throw new RuntimeException(&quot;Radius should be &gt;= 0&quot;);\n        }\n        this.radius = radius;\n    }\n\n    public int getRadius() {\n        return this.radius;\n    }\n}\n</code></pre>\n<p>The radius is not allowed to be negative. Here's a suclass:</p>\n<pre><code>class ColoredCircle extends Circle {\n    private Color color; // defined elsewhere\n\n    public ColoredCircle(int radius, Color color) {\n        super(radius);\n        this.color = color;\n    }\n\n    public Color getColor() {\n        return this.color;\n    }\n}\n</code></pre>\n<p>This subclass is a subtype of <code>Circle</code>, according to the LSP.</p>\n<p>The LSP states that:</p>\n<blockquote>\n<p>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. <em>(Barbara Liskov, &quot;Data Abstraction and Hierarchy&quot;, SIGPLAN Notices, 23,5 (May, 1988))</em></p>\n</blockquote>\n<p>Here, for each <code>ColoredCircle</code> instance <code>o1</code>, consider the <code>Circle</code> instance having the same radius <code>o2</code>. For every program using <code>Circle</code> objects, if you replace <code>o2</code> by <code>o1</code>, the behavior of any program using <code>Circle</code> will remain the same after the substitution. (Note that this is theoretical : you will exhaust the memory faster using <code>ColoredCircle</code> instances than using <code>Circle</code> instances, but that's not relevant here.)</p>\n<p>How do we find the <code>o2</code> depending on <code>o1</code> ? We just strip the <code>color</code> attribute and keep the <code>radius</code> attribute. I call the transformation <code>o1</code> -&gt; <code>o2</code> a <em>projection</em> from the <code>CircleColor</code> space on the <code>Circle</code> space.</p>\n<h1>Counter Example</h1>\n<p>Let's create another example to illustrate the violation of the LSP.</p>\n<h2><code>Circle</code> and <code>Square</code></h2>\n<p>Imagine this subclass of the previous <code>Circle</code> class:</p>\n<pre><code>class Square extends Circle {\n    private int sideSize;\n\n    public Square(int sideSize) {\n        super(0);\n        this.sideSize = sideSize;\n    }\n\n    @Override\n    public int getRadius() {\n        return -1; // I'm a square, I don't care\n    }\n\n    public int getSideSize() {\n        return this.sideSize;\n    }\n}\n</code></pre>\n<h2>The violation of the LSP</h2>\n<p>Now, look at this program :</p>\n<pre><code>public class Liskov {\n    public static void program(Circle c) {\n        System.out.println(&quot;The radius is &quot;+c.getRadius());\n    }\n</code></pre>\n<p>We test the program with a <code>Circle</code> object and with a <code>Square</code> object.</p>\n<pre><code>    public static void main(String [] args){\n        Liskov.program(new Circle(2)); // prints &quot;The radius is 2&quot;\n        Liskov.program(new Square(2)); // prints &quot;The radius is -1&quot;\n    }\n}\n</code></pre>\n<p>What happened ? Intuitively, although <code>Square</code> is a subclass of <code>Circle</code>, <code>Square</code> is <em>not</em> a subtype of <code>Circle</code> because no regular <code>Circle</code> instance would ever have a radius of -1.</p>\n<p>Formally, this is a violation of Liskov Substitution Principle.</p>\n<p>We have a program defined in terms of <code>Circle</code> and there is no <code>Circle</code> object that can replace <code>new Square(2)</code> (or any <code>Square</code> instance by the way) in this program and leave the behavior unchanged: remember that radius of any <code>Circle</code> is always positive.</p>\n<h1>Subclass and subtype</h1>\n<p>Now we know why a <strong>subclass</strong> is not always <strong>subtype</strong>. When a subclass is not a subtype, i.e. when there is a LSP violation, the behavior of some programs (at least one) won't always be the expected behavior. This is very frustrating and is usually interpreted as a bug.</p>\n<p>In an ideal world, the compiler or interpreter would be able to check is a given subclass is a real subtype, but we are not in an ideal world.</p>\n<h2>Static typing</h2>\n<p>If there is some static typing, you are bound by the superclass signature at compile time. <code>Square.getRadius()</code> can't return a <code>String</code> or a <code>List</code>.</p>\n<p>If there is no static typing, you'll get an error at runtime if the type of one argument is wrong (unless the typing is weak) or the number of arguments is inconsistent (unless the language is very permissive).</p>\n<p><em>Note about the static typing: there is a mechanism of covariance of the return type (a method of S can return a subclass of the return type of the same method of T) and contravariance of the parameters types (a method of S can accept a superclass of a parameter of the same parameter of the same method of T). That is a specific case of precondition and postcondition explained below.</em></p>\n<h2>Design by contract</h2>\n<p>There's more. Some languages (I think of Eiffel) provide a mechanism to enforce the compliance with the LSP.</p>\n<p>Let alone the determination the projection <code>o2</code> of the initial object <code>o1</code>, we can expect the same behavior of any program if <code>o1</code> is substituted for <code>o2</code> if, <strong>for any argument <code>x</code> and any method <code>f</code></strong>:</p>\n<ul>\n<li>if <code>o2.f(x)</code> is a valid call, then <code>o1.f(x)</code> should also be a valid call (1).</li>\n<li>the result (return value, display on console, etc.) of <code>o1.f(x)</code> should be equal to the result of <code>o2.f(x)</code>, or at least equally valid (2).</li>\n<li><code>o1.f(x)</code> should let <code>o1</code> in an internal state and <code>o2.f(x)</code> should let <code>o2</code> in an internal state so that next function calls will ensure that (1), (2) and (3) will still be valid (3).</li>\n</ul>\n<p>(<em>Note that (3) is given for free if the function <code>f</code> is pure. That's why we like to have immutable objects.</em>)</p>\n<p>These conditions are about the <strong>semantics</strong> (what to expect) of the class, not only the syntax of the class. Also, these conditions are very strong. But they can be approximated by assertions in design by contract programming. These assertions are a way to ensure that the semantic of the type is upheld. Breaking the contract leads to runtime errors.</p>\n<ul>\n<li>The precondition defines what is a valid call. When subclassing a class, the precondition may only be weakened (<code>S.f</code> accepts more than <code>T.f</code>) (a).</li>\n<li>The postcondition defines what is a valid result. When subclassing a class, the postcondition may only be strengthened (<code>S.f</code> provides more than <code>T.f</code>) (b).</li>\n<li>The invariant defines what is a valid internal state. When subclassing a class, the invariant must remain the same (c).</li>\n</ul>\n<p>We see that, roughly, (a) ensures (1) and (b) ensures (2), but (c) is weaker than (3). Moreover, assertions are sometimes difficult to express.</p>\n<p>Think of a class <code>Counter</code> having a unique method <code>Counter.counter()</code> that returns the next integer. How do you write a postcondition for that ? Think of a class <code>Random</code> having a method <code>Random.gaussian()</code> that returns a float between 0.0 and 1.0 . How do you write a postcondition to check that the distribution is gaussian ? It may be possible, but the cost would be so high that we would rely on test rather than on postconditions.</p>\n<h1>Conclusion</h1>\n<p>Unfortunately, a subclass is not always a subtype. This can lead to an unexpected behavior -- a bug.</p>\n<p>OOP languages provide mechanism to avoid this situation. At syntactic level first. At semantical level too, depending on the programming language: a part of the semantics can be encoded in the text of the program using assertions. But it's up to you to ensure that a subclass is a subtype.</p>\n<p>Remember when you began to learn OOP ? &quot;If the relation is IS-A, then use inheritance&quot;. That's true the other way: <strong>if you use inheritance, be sure that the relation is IS-A</strong>.</p>\n<p>The LSP defines, at a higher level than assertions, what is a subtype. Assertions are a valuable tool to ensure that the LSP is upheld.</p>\n"}, {'answer_id': 70356938, 'author': 'DRAGON-PARTY', 'author_id': 12232720, 'author_profile': 'https://Stackoverflow.com/users/12232720', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n<p>Let q(x) be a property provable about objects of x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.</p>\n</blockquote>\n<hr />\n<p>Actually, the accepted answer is not a counterexample for the Liskov principle. A square naturally is a specific rectangle, so it makes perfect sense that inherits from the class rectangle. You simply need to implement it in this way:</p>\n<pre><code>@Override\npublic void setHeight(double height) {\n   this.height = height;\n   this.width = height; // since it's a square\n}\n\n@Override\npublic void setWidth(double width) {\n   setHeight(width);\n}\n</code></pre>\n<hr />\n<p>So, having provided a good example, this, however, is a counterexample:</p>\n<pre><code>class Family:\n-- getChildrenCount()\n\nclass FamilyWithKids extends Family:\n-- getChildrenCount() { return childrenCount; } // always &gt; 0\n\nclass DeadFamilyWithKids extends FamilyWithKids:\n-- getChildrenCount() { return 0; }\n-- getChildrenCountWhenAlive() { return childrenCountWhenAlive; }\n</code></pre>\n<p>In this implementation, <code>DeadFamilyWithKids</code> cannot inherit from <code>FamilyWithKids</code> since <code>getChildrenCount()</code> returns <code>0</code>, while from <code>FamilyWithKids</code> it should always return something greater <code>0</code>.</p>\n"}]
['https://Stackoverflow.com/questions/56860', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/303/']