clean-code-javascript icon indicating copy to clipboard operation
clean-code-javascript copied to clipboard

"Bad" example for Liskov Substitution Principle does not give incorrect result

Open jamesirving opened this issue 5 years ago • 1 comments

As stated in the description:

"The best explanation for this is if you have a parent class and a child class, then the base class and child class can be used interchangeably without getting incorrect results"

However, in the "Bad" example, the results are 20, 20, and 25. Which is the expected result, as far as I can tell is, in fact, correct and is the same result as the "Good" example.

jamesirving avatar Feb 11 '20 00:02 jamesirving

The "bad" example is correct, but admittedly I think Robert Martin explained it better by putting an assert in the code.

void g(Rectangle& r)
{
    r.SetWidth(5);
    r.SetHeight(4);
    assert(r.GetWidth() * r.GetHeight()) == 20);
}

If you pass a Square to this function, the result will not be 20 and the assert will fail. The issue wasn't that a square makes 25. The issue was that a square should not inherit from rectangle, because a rectangle cannot be substituted with a square.

Jeff-Mott-OR avatar Feb 14 '20 19:02 Jeff-Mott-OR