Principles Patterns Follow: Liskov Substitution
Barbara Liskov's (1994) research showed that clients that use base classes must be able to use objects of derived classes without changing.
When a class is derived from a base class, we traditionally call this an “is-a” relationship. But Liskov suggests that 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 a scheduling system. The system began with the concept of an “event,” which had a start date, end date, start time, and end time.
Later, a “daylong event” was added by subclassing “event,” since a “daylong event is an event.” However, the “daylong 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. Daylong events that were 12:00 a.m. to 12:00 a.m. in one time zone were 9:00 p.m. to 9:00 p.m. in others, spanning two actual days.
This time-zone adjustment worked properly for “events,” but did not work for “daylong events” because a 24-hour period is not always a day, but often involves two days; they did not “behave” the same way and, therefore, were not substitutable.
The abstraction should have been “event,” with two separate implementations: “daylong event” and “timed event.” There should have been no inheritance relationship between them. The patterns operate this way.