The Liskov Substitution Principle (LSP) on Wikipedia
Say I have a Alien
class with an numFingers
attribute*. Occasionally, I need to pull the sum of the numFingers
from the database, grouped by other field values. In these cases, I have no need to manipulate each record individually, but I do need access to a lot of their functionality -- be able to get attributes, perform some basic logic on them, etc. This may include data summed from thousands of records, so it makes little sense to instantiate thousands of Alien
objects when the database query can do the work of summing for me.
I would like to make an extension class called AlienAggregate
, whose attributes are set from the grouped & summed query. This class would allow me to call any of Alien
's methods. The only difference between functionality of the two classes, is GetID()
. The aggregate class has no ID, since its data has been derived from any number of records. Because of this, calling GetID()
on AlienAggregate
throws an exception.
Is this a violation of the Liskov Substitution Principle? Is there a better way to handle a call to GetID()
? Is there a better way to design the relationship between the Alien
and AlienAggregate
classes?
*Actual names may have been changed just because I c开发者_开发百科an.
I don't think you're violating LSP
since the principle only applies when Alien
is a subtype of AlienAggregate
(or the other way around). There is no is a
relationship here (more of an aggregation of Alien
's as you've appropriately named them).
Instead, it sounds like both Alien
, and AlienAggregate
probably implement a LooksAlien
Interface. The Alien
class just has an additional method, GetID().
...just beware of the nefarious BeginInvasion
method on AlienAggregate
.
精彩评论