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’t1. 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 evil2.


  1. 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. 
  2. They can also be useful as well; there is very little (nothing?) that isn’t subject to abuse. 
Advertisements

Author: Robert Watkins

My name is Robert Watkins. I am a software developer and have been for over 18 years now. I currently work for people, but my opinions here are in no way endorsed by them (which is cool; their opinions aren’t endorsed by me either). My main professional interests are in Java development, using Agile methods, with a historical focus on building web based applications. I’m also a Mac-fan and love my iPhone, which I’m currently learning how to code for. I live and work in Brisbane, Australia, but I grew up in the Northern Territory, and still find Brisbane too cold (after 16 years here). I’m married, with two children and one cat. My politics are socialist in tendency, my religious affiliation is atheist (aka “none of the above”), my attitude is condescending and my moral standing is lying down.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s