![]() However, there are other, far more subtle, ways of violating the LSP.Ĭonsider an application which uses the Rectangle class as describedĭouble GetHeight() const Square and Rectangle, a More Subtle Violation. Indeed, many view the structure of this function as anathema to Object Oriented Design. Whenever new derivatives of Shape are created. It must know aboutĮvery possible derivative of the Shape class, and it must be changed i.e.: void DrawShape(const Shape& s)Ĭlearly the DrawShape function is badly formed. ![]() Run-Time Type Information (RTTI) to select a function based upon the One of the most glaring violations of this principle is the use of C++ Some relevant parts of the paper (note that the second example is heavily condensed): A Simple Example of a Violation of LSP It discusses subtle and not-so-subtle ways in which the principle may be violated. Robert Martin has an excellent paper on the Liskov Substitution Principle. This allows us to use good object oriented principles like encapsulation and reuse and doesn’t violate LSP. Instead of extending Board, ThreeDBoard should be composed of Board objects. A unit of code attempting to use the ThreeDBoard class as its base class Board would be very out of luck. The Z parameter has no context to the Board class and the inherited methods from the Board class lose their meaning. So you must implement those methods again with a Z parameter. The methods for AddUnit, GetTile, GetUnits and so on, all take both X and Y parameters in the Board class but the ThreeDBoard needs a Z parameter as well. Where it breaks down is when you look at all the other members inherited from Board. Board provides both the Height and Width properties and ThreeDBoard provides the Z axis. So a ThreeDBoard class is introduced that extends Board.Īt first glance this seems like a good decision. 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. This will allow a game developer to manage units in the board during the course of the game. They present a class that represents a board that looks like this:Īll of the methods take X and Y coordinates as parameters to locate the tile position in the two-dimensional array of Tiles. They present a scenario where you are a developer on a project to build a framework for strategy games. The most effective way I have seen to illustrate this point was in Head First OOA&D. use another strategy such as composition to achieve your goal. The Liskov Substitution Principle (LSP, lsp) is a concept in Object Oriented Programming that states:Īt its heart LSP is about interfaces and contracts as well as how to decide when to extend a class vs.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |