Does this solve the Liskov Substitution square-rectangle violation?

前端 未结 2 1742
离开以前
离开以前 2021-01-20 03:14

I\'m very new to the SOLID design principles. One thing I had problem with understanding is the \"Square-rectangle\" example of a Liskov Substition Principle violation. Why

2条回答
  •  粉色の甜心
    2021-01-20 03:57

    The LSP states that substituting an object of a subclass should not change the behaviour, or the correctness, of the program. The classes you specify do change the correctness. With a rectangle, the client of the class expects that the height and width are independently settable. When you subclass with Square, this is no longer the case.

    A client setting a width of 5 and a height of 10, whilst reference an object that happens to be a Square but is held in a Rectangle variable, will get different results according to the order in which they set the height and width properties. They might get a 5x5 rectangle or a 10x10 one. Either case will be unexpected.

    There's Barbara's original complex description of LSP but Uncle Bob's makes it easier - "Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it". This is broken with the Square/Rectangle problem.

    I wrote an article about this at http://www.blackwasp.co.uk/SquareRectangle.aspx.

提交回复
热议问题