Circle-ellipse problem

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
m (Added a link)
m
 
Line 15: Line 15:
 
*[[Liskov substitution principle]]
 
*[[Liskov substitution principle]]
 
*[[Design by contract]]
 
*[[Design by contract]]
 +
 +
{{Design Anti-patterns}}
 +
[[Category: Anti-Patterns]]

Latest revision as of 02:25, 22 July 2009

This anti pattern illustrates the difficulties when using inheritance in object oriented systems. It occurs when inheritance is not used properly and the Liskov substitution principle is violated.

This problem is also known as the Square-rectangle problem. It occurs for example when Square inherits from Rectangle or Circle inherits from Ellipse. While these inheritance relationships may make sense conceptually (and mathematically), they constitute a violation of the Liskov substitution principle. It may make sense that Square is a Rectangle and Circle is an Ellipse and inheritance may therefore appear appropriate. However, this illustrates that while inheritance is often seen as an is-a relationship, it is more complex.

To understand why this kind of inheritance is a bad idea, let us consider a Square class which inherits from a Rectangle class. A Rectangle has a width and height and getters and setters for width and height. A Square inherits from Rectangle but adds the requirement that width and height should always be the same. However, now we have the situation where superclass methods can potentially invalidate an invariant specified in the base class.

We can override the setters in the Square class to ensure that if the width is changed, the height is also changed but this means that we have now violated the contract of those methods as established by the Rectangle class.

Because of polymorphism, a Square can be used where a Rectangle is expected, potentially without the client knowing that it is given a Square rather than a simple rectangle. When the client calls the setters for width and height, it therefore does not expect the additional side effects caused by the overridden methods in Square which violate the contract defined in the Rectangle class. Clearly, this is a bad idea. It is a violation of the Liskov substitution principle because a Square cannot really be provided where a rectangle is expected.

Liabilities

  • The contracts of methods in the superclass may be violated. This can be potentially confusing for clients and can introduce bugs and have a negative effect on maintainability.

Related design maxims


Personal tools