« Why some web frameworks don't distinguish between GET and POST | Main | Mixing <ant> and <subant> leads to confusion... »

Circle/Ellipse Paradox... NOT!

There's a (somewhat controversial) design principle in object-oriented programming called the Liskov Substitution Principle. One of the classic examples is about Circles being Ellipses.

The example goes to show how a Circle shouldn't extend an Ellipse (implementation-wise) because a Circle has constraints that an Ellipse doesn't2. Thus, you can't substitute a Circle where you can use an Ellipse, because the client can break. In Java terms, think of the Circle throwing an exception that the Ellipse doesn't.

The problem here is that the wrong type is being substituted. The key to getting around this argument (if you care) is to think of the unconstrained Ellipse as being a special case (subclass) of an Ellipse that is potentially constrained in every way possible. This then makes the Circle a special case of the potentially constrained Ellipse as well.

Sure, you can't substitue a Circle for an UnconstrainedEllipse, but you can substitue either for a PossiblyConstrainedEllipse, and thus preserve the LSP.

PS: The LSP isn't just about type substitution, but about the safety of doing so. If you didn't care about safety, you can subclass an Ellipse in Java and make it a circle via RuntimeExceptions. However, your client code may get upset. One of the many reasons RuntimeExceptions can be evil[3.]

----

[2] The difference: an ellipse has two focus points that define its shape. A circle, mathematically, is an ellipse where the two foci coincide, effectively giving it one focus point.

[3] They can also be useful as well; there is very little (nothing?) that isn't subject to abuse.

Post a comment


About

This page contains a single entry from the blog posted on June 17, 2004 8:28 PM.

The previous post in this blog was Why some web frameworks don't distinguish between GET and POST.

The next post in this blog is Mixing <ant> and <subant> leads to confusion....

Many more can be found on the main index page or by looking through the archives.

Creative Commons License
This weblog is licensed under a Creative Commons License.
Powered by
Movable Type 3.35