Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<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> <blockquote> <p>Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.</p> </blockquote> <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> <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> <p>They present a class that represents a board that looks like this:</p> <p><img src="https://oncodebynotmyself.files.wordpress.com/2011/03/board_thumb.png" alt="Class Diagram"></p> <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> <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> <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> <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> <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> <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> <p>This allows us to use good object oriented principles like encapsulation and reuse and doesn’t violate LSP.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload