I have this dilemma where i need to choose between differant types of inheritance for the Gregorian and Julian calanders. I want to have one class named Date as a base class. My question is as follows: Should I have a class for the Gregorian that inherits from the date class and Julian that does the same? Or should only the Gregorian class inherit from the Date and Julian inherit from the Gregorian, or vice versa? Or should I have a class beneath the Date that inherits from Date and have the Gregorian and Julian inherit from that class?
Date Date Date 开发者_开发问答 Date
Gregorian Julian Gregorian Julian New class
Julian Gregorian Gregorian Julian
I would personally choose the first alternative where the both inherit from Date, is this a good choice. Can i get som opinions about this?
I don't know the inner details of the calendar systems, but I'm sure it is hard not to underestimate their subtle complexities. That alone would make me absolutely not want to mix the implementation in a class hierarchy.
I'd go with
- separate classes (types)
- optional non-implicit conversions
- shared utilities from a policy/strategy class to avoid unwanted code duplication
PS. In the classical 'Liskov' sense, you could have an abstract base class Date that just 'names' concepts common to all (most?) calendar systems. However, I'm really doubting what the added value would be. I could see it lead to a lot of confusion (it invites code to mix subtypes of Date in any or all code and all code using your datetime classes must be prepared to handle the whole gamut always).
By the way, have a look at Noda Time and Joda Time. These well-respected libraries are generally thought to be especially well-designed.
Gregorian and Julian calendars are two types of calendar. It would be better for them to inherit from a common base class than inherit from each other.
An example can be found in Joda time, which has Gregorian and Julian chronologies as different subclases from a common base chronology.
A counter-example can be found in the standard Java library, in which the Gregorian and Julian calendars are supported by the same class.
A Calendar
is not a Date
so there is no need for either to inherit from Date
.
At most, a Calendar
should operate on Dates
. Or perhaps a Date
could convert itself from one kind to another.
What exactly are you trying to do and why isn't it already done in a 3rd party library already?
精彩评论