继承和LSP
提前为一个冗长的问题道歉。在此特别感谢反馈。 。 。
在我的工作中,我们用日期范围(日期周期,如果你愿意的话)做很多事情。我们需要进行各种测量,比较两个日期周期之间的重叠等。我设计了一个接口、一个基类和几个派生类,这些类可以很好地满足我迄今为止的需求:
- IDatePeriod
- DatePeriod
- CalendarMonth
- CalendarWeek
- FiscalYear
剥离其本质, DatePeriod 超类如下(省略了所有令人着迷的功能,这些功能是我们需要这组类的基础......):(
Java 伪代码):
class datePeriod implements IDatePeriod
protected Calendar periodStartDate
protected Calendar periodEndDate
public DatePeriod(Calendar startDate, Calendar endDate) throws DatePeriodPrecedenceException
{
periodStartDate = startDate
. . .
// Code to ensure that the endDate cannot be set to a date which
// precedes the start date (throws exception)
. . .
periodEndDate = endDate
{
public void setStartDate(Calendar startDate)
{
periodStartDate = startDate
. . .
// Code to ensure that the current endDate does not
// precede the new start date (it resets the end date
// if this is the case)
. . .
{
public void setEndDate(Calendar endDate) throws datePeriodPrecedenceException
{
periodEndDate = EndDate
. . .
// Code to ensure that the new endDate does not
// precede the current start date (throws exception)
. . .
{
// a bunch of other specialty methods used to manipulate and compare instances of DateTime
}
基类包含一堆用于操作日期周期类的相当专业的方法和属性。派生类仅更改相关期间的起点和终点的设置方式。例如,对我来说,CalendarMonth 对象确实“是一个”DatePeriod 是有意义的。但是,出于显而易见的原因,日历月具有固定的持续时间,并且具有特定的开始和结束日期。事实上,虽然 CalendarMonth 类的构造函数与超类的构造函数相匹配(因为它具有 startDate 和 endDate 参数),但这实际上是简化构造函数的重载,它只需要一个 Calendar 对象。
对于 CalendarMonth,提供任何 日期都将生成一个 CalendarMonth 实例,该实例从相关月份的第一天开始,到该月的最后天结束月。
public class CalendarMonth extends DatePeriod
public CalendarMonth(Calendar dateInMonth)
{
// call to method which initializes the object with a periodStartDate
// on the first day of the month represented by the dateInMonth param,
// and a periodEndDate on the last day of the same month.
}
// For compatibility with client code which might use the signature
// defined on the super class:
public CalendarMonth(Calendar startDate, Calendar endDate)
{
this(startDate)
// The end date param is ignored.
}
public void setStartDate(Calendar startDate)
{
periodStartDate = startDate
. . .
// call to method which resets the periodStartDate
// to the first day of the month represented by the startDate param,
// and the periodEndDate to the last day of the same month.
. . .
{
public void setEndDate(Calendar endDate) throws datePeriodPrecedenceException
{
// This stub is here for compatibility with the superClass, but
// contains either no code, or throws an exception (not sure which is best).
{
}
对冗长的序言表示歉意。鉴于上述情况,这种类结构似乎违反了里氏替换原则。虽然在任何可能使用更通用的 DatePeriod 类的情况下都可以使用 CalendarMonth 的实例,但关键方法的输出行为将有所不同。换句话说,人们必须意识到在给定情况下正在使用 CalendarMonth 的实例。
虽然 CalendarMonth(或 CalendarWeek 等)遵守通过基类使用 IDatePeriod 建立的契约,但在使用 CalendarMonth 且预期普通旧 DatePeriod 的行为的情况下,结果可能会变得严重偏差。 。 。 (请注意,基类上定义的所有其他时髦方法都可以正常工作 - 只是开始和结束日期的设置在 CalendarMonth 实现中有所不同)。
是否有更好的方法来构建此结构,以便在不影响可用性和/或重复代码的情况下保持对 LSP 的正确遵守?
Apologies in advance for a long-winded question. Feedback especially appreciated here . . .
In my work, we do a lot of things with date ranges (date periods, if you will). We need to take all sorts of measurements, compare overlap between two date periods, etc. I have designed an Interface, a base class, and several derived classes which serve my needs well to date:
- IDatePeriod
- DatePeriod
- CalendarMonth
- CalendarWeek
- FiscalYear
Stripped to its essentials, the DatePeriod superclass is as follows (omits all the fascinating features which are the basis for why we need this set of classes . . .):
(Java pseudocode):
class datePeriod implements IDatePeriod
protected Calendar periodStartDate
protected Calendar periodEndDate
public DatePeriod(Calendar startDate, Calendar endDate) throws DatePeriodPrecedenceException
{
periodStartDate = startDate
. . .
// Code to ensure that the endDate cannot be set to a date which
// precedes the start date (throws exception)
. . .
periodEndDate = endDate
{
public void setStartDate(Calendar startDate)
{
periodStartDate = startDate
. . .
// Code to ensure that the current endDate does not
// precede the new start date (it resets the end date
// if this is the case)
. . .
{
public void setEndDate(Calendar endDate) throws datePeriodPrecedenceException
{
periodEndDate = EndDate
. . .
// Code to ensure that the new endDate does not
// precede the current start date (throws exception)
. . .
{
// a bunch of other specialty methods used to manipulate and compare instances of DateTime
}
The base class contains a bunch of rather specialized methods and properties for manipulating the date period class. The derived classes change only the manner in which the start and end points of the period in question are set. For example, it makes sense to me that a CalendarMonth object indeed "is-a" DatePeriod. However, for obvious reasons, a calendar month is of fixed duration, and has specific start and end dates. In fact, while the constructor for the CalendarMonth class matches that of the superclass (in that it has a startDate and endDate parameter), this is in fact an overload of a simplified constructor, which requires only a single Calendar object.
In the case of CalendarMonth, providing any date will result in a CalendarMonth instance which begins on the first day of the month in question, and ends on the last day of that same month.
public class CalendarMonth extends DatePeriod
public CalendarMonth(Calendar dateInMonth)
{
// call to method which initializes the object with a periodStartDate
// on the first day of the month represented by the dateInMonth param,
// and a periodEndDate on the last day of the same month.
}
// For compatibility with client code which might use the signature
// defined on the super class:
public CalendarMonth(Calendar startDate, Calendar endDate)
{
this(startDate)
// The end date param is ignored.
}
public void setStartDate(Calendar startDate)
{
periodStartDate = startDate
. . .
// call to method which resets the periodStartDate
// to the first day of the month represented by the startDate param,
// and the periodEndDate to the last day of the same month.
. . .
{
public void setEndDate(Calendar endDate) throws datePeriodPrecedenceException
{
// This stub is here for compatibility with the superClass, but
// contains either no code, or throws an exception (not sure which is best).
{
}
Apologies for the long preamble. Given the situation above, it would seem this class structure violates the Liskov substitution principle. While one CAN use an instance of CalendarMonth in any case in which one might use the more general DatePeriod class, the output behavior of key methods will be different. In other words, one must be aware that one is using an instance of CalendarMonth in a given situation.
While CalendarMonth (or CalendarWeek, etc.) adhere to the contract established through the base class' use of IDatePeriod, results might become horribly skewed in a situation in which the CalendarMonth was used and the behavior of plain old DatePeriod was expected . . . (Note that ALL of the other funky methods defined on the base class work properly - it is only the setting of start and end dates which differs in the CalendarMonth implementation).
Is there a better way to structure this such that proper adherence to LSP might be maintained, without compromising usability and/or duplicating code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这看起来与通常关于正方形和矩形的讨论类似。虽然正方形是一个矩形,但是 Square 继承自 Rectangle 并没有什么用处,因为它不能满足 Rectangle 的预期行为。
您的 DatePeriod 有 setStartDate() 和 setEndDate() 方法。对于 DatePeriod,您会期望两者可以按任何顺序调用,不会相互影响,并且也许它们的值将精确指定开始和结束日期。但对于 CalendarMonth 实例,情况并非如此。
也许,不是让 CalendarMonth 扩展 DatePeriod,而是两者都可以扩展一个公共抽象类,该抽象类仅包含与两者兼容的方法。
顺便说一句,根据您问题的深思熟虑,我猜您已经考虑过寻找现有的日期库。以防万一您还没有,请务必查看 Joda 时间 库,其中包括可变和不可变周期的类。如果现有的库解决了您的问题,您可以专注于自己的软件,并让其他人支付设计、开发和维护时间库的成本。
编辑:注意到我将您的 CalendarMonth 类称为“日历”。为清楚起见已修复。
This seems similar to the usual discussion about Squares and Rectangles. Although a square is-a rectangle, it's not useful for Square to inherit from a Rectangle, because it cannot satisfy the expected behavior of a Rectangle.
Your DatePeriod has a setStartDate() and setEndDate() method. With a DatePeriod, you would expect that the two could be called in any order, would not affect each other, and maybe that their values would precisely specify a start and end date. But with a CalendarMonth instance, that's not true.
Maybe, instead of having CalendarMonth extend DatePeriod, the two could both extend a common abstract class, that contains only methods compatible with both.
By the way, based on the thoughtfulness of your question, I'm guessing you've already thought to look for existing date libraries. Just in case you haven't, be sure to take a look at the Joda time library, which includes classes for mutable and immutable periods. If an existing library solves your problem, you could concentrate on your own software, and let someone else pay the cost of designing, developing and maintaining the time library.
Edit: Noticed I had referred to your CalendarMonth class as Calendar. Fixed for clarity.
我认为建模问题在于您的
CalendarMonth
类型实际上并不是不同的种类时期。相反,它是一个用于创建此类周期的构造函数,或者,如果您愿意的话,工厂函数。我将消除
CalendarMonth
类并创建一个名为Periods
的实用程序类,其中包含私有构造函数和返回各种IDatePeriod
的各种公共静态方法> 实例。这样,我们就可以编写
,并且
wholeMonthBounding()
函数的文档将解释调用者对返回的IDatePeriod
实例的期望。 Bikeshedding,此函数的另一个名称可以是wholeMonthContaining()
。考虑一下您打算如何处理“经期”。如果目标是进行“遏制测试”,如“这一刻是否在某个时期内?”,那么您可能想承认无限和半有界的时期。
这表明您需要定义一些包含谓词类型,例如
然后前面提到的
Periods
类(也许最好通过此阐述命名为PeriodPredicates
)可以公开更多类似的函数足够的推动力。如果您需要任何说明,请告诉我。
I think the modeling problem is that your
CalendarMonth
type isn't really a different kind of period. Rather, it's a constructor or, if you prefer, factory function for creating such periods.I'd eliminate the
CalendarMonth
class and create a utility class called something likePeriods
, with a private constructor and various public static methods that return variousIDatePeriod
instances.With that, one could write
and the documentation for the
wholeMonthBounding()
function would explain what the caller can expect of the returnedIDatePeriod
instance. Bikeshedding, an alternate name for this function could bewholeMonthContaining()
.Consider what you intend to do with your "periods". If the goal is do "containment testing", as in "Does this moment sit within some period?", then you might like to acknowledge infinite and half-bounded periods.
That suggests that you'd define some containment predicate type, such as
Then the aforementioned
Periods
class—perhaps bettern namedPeriodPredicates
with this elaboration—could expose more functions likeThat should be enough of a push. Let me know if you need any clarification.
通常,遵守 LSP 就是要仔细记录基类或接口的功能。
例如,在 Java 中
Collection
有一个名为add(E)
的方法。它可能有这个文档:但如果确实如此,那么维护无重复不变量的
Set
将很难不违反LSP。因此,add(E)
的记录如下:现在,没有客户端可以使用
Collection
并期望该元素始终会被添加,即使它已经存在于集合中。我没有太深入地研究你的例子,但我觉得你也许可以同样小心。如果您在日期周期界面中,
setStartDate()
的记录如下:没有进一步指定任何内容?或者甚至,
setEndDate()
可以实现并进行类似的记录。那么具体的实现如何打破LSP呢?注意 还值得一提的是,如果使类不可变,则更容易满足 LSP。
Often times adhering to the LSP is a matter of being meticulous about documenting what the base class or interface does.
For instance, in Java
Collection
has a method namedadd(E)
. It could have this documentation:But if it did, then it would be very difficult for a
Set
, which maintains a no-duplicates invariant, to not violate the LSP. So instead,add(E)
is documented like this:Now no client can use a
Collection
and expect that the element will always be added even if it already existed in the collection.I haven't looked too in-depth at your example, but it strikes me you might be able to be as careful. What if your in your date period interface,
setStartDate()
was documented like this:Without specifying anything further? Or even,
setEndDate()
could be implemented and be similarily documented. How then would a concrete implementation break the LSP?Note It is also worth mentioning that it's a lot easier to satisfy LSP if you make your class immutable.
这确实违反了 LSP,与经典的椭圆和圆示例完全相同。
如果您希望
CalendarMonth
扩展DatePeriod
,则应该使DatePeriod
不可变。然后,您可以将所有变异方法更改为返回新
DatePeriod
的方法并保持所有内容都很好地不可变,或者创建不尝试处理年、月、周等的备用可变子类。This certainly does violate LSP, in exactly same way as the classic Ellipse and Circle example.
If you want
CalendarMonth
to extendDatePeriod
, you should makeDatePeriod
immutable.You can then either change all the mutating methods to ones that return a new
DatePeriod
and keep everything nicely immutable, or make alternate mutable subclass that doesn't try to deal with years, months, weeks and such.