Reputation: 157
I am able to get the general idea of LSP and its violations. Say, Square extending a Rectangle having setWidth() and setHeight() functions is a subtle violation of LSP because there is an extra requirement. Similarly a GreenDuck extending a Duck class with a function something(Grass g) must not have an extra clause requiring the grass to be green.
For the square and rectangle scenario, I think it would be right to implement a polygon interface and the rectangle and the square class implementing polygon in their own ways. For the GreenDuck scenario, GreenDuck using composition to have Duck as one of its fields might be a good idea.
Q1) Is my understanding correct of the above 2 scenarios?
Q2) Also, I am unable to model scenarios where LSP would allow for 'extends' which brings me to the question. Can someone delve into LSP and provide specific examples where extends would be appropriate and bonus if it is something where composition wouldn't be as good.
Edit: for clarity
Upvotes: 1
Views: 138
Reputation: 41474
In the context of Liskov, it's important to distinguish between inspection interfaces and modification interfaces. A square "is-a" rectangle in the sense that, like a rectangle, you can get its height, and its width. It is different from a rectangle in that you can't set its height and width separately. So if by "it would be right to implement a polygon interface" you mean that Rectangle
should have a getPolygonVertices
function, then sure, that's fine. But if you mean that it should implement an interface that has setPolygonVertices
then that's wrong, for the same reason that Square
can't have a setHeightAndWidth
like Rectangle
.
As for GreenDuck
having a Duck
member.... eeeh... that would be kind of weird. Do ducks generally have other ducks inside them?
Upvotes: 3