Barbara Liskov (1987) stated, “Clients that use base classes must be able to use objects of derived classes without changing” (paraphrased).
When a class is derived from a base class, traditionally we call this an “is-a” relationship. But Liskov suggests we should instead consider it to be a “behaves-like” relationship and, when this determined to be untrue, then perhaps inheritance is being misused.
One place where I saw this in action was in scheduling. The system began with the concept of an “Event,” which had a start date, end date, start time, and end time.
Later, a “Day-Long Event” was added by sub-classing “Event” since a “Day-Long Event is an Event.” However, the Day-Long Event was altered such that the start and end times were locked at midnight-to-midnight since a “day is a 24-hour period.”
This caused problems when support for different time zones was added. Day-Long Events that were 12 AM-12 AM in one zone were 9 PM – 9 PM in others, spanning two days… A 24-hour period is not always a day; they did not “behave” the same way and therefore were not substitutable.
The patterns rigorously avoid this kind of mistake.
This is Scott Bain. Visit us at www.netobjectives.com.