views:

78

answers:

2

I will use (again) the following class hierarchy:

Event

and all the following classes inherit from Event:

SportEventType1 SportEventType2 SportEventType3 SportEventType4

I have originally designed the Event class like this:

public abstract class Event
{
    public abstract EventType EventType { get; }
    public DateTime Time { get; protected set; }

    protected Event(DateTime time) {
        Time = time;
    }
}

with EventType being defined as:

public enum EventType {
    Sport1,
    Sport2,
    Sport3,
    Sport4
}

The original idea would be that each SportEventTypeX class would set its correct EventType. Now that I think of it, I think this approach is totally incorrect for the following reasons:

  1. If I want to later add a new SportEventType class I will have to modify the enum
  2. If I later decide to remove one SportEventType that I feel I won't use I'm also in big trouble with the enum.
  3. I have a class variable in the Event class that makes, afterall, assumptions about the kind of classes that will inherit from it, which kinda defeats the purpose of inheritance.

How would you solve this kind of situation? Define in the Event class an abstract "Description" property, having each child class implement it? Having an Attribute(Annotation in Java!) set its Description variable instead? What would be the pros/cons of having a class variable instead of attribute/annotation in this case? Is there any other more elegant solution out there?

Thanks

+1  A: 

You could simply use the is operator and forget about an enum.

var myEvent = Event.Create(type);

if (myEvent is BaseballGame)
{
    // ...
}
ChaosPandion
Ideally, you want to avoid this as much as possible, though. If you have "event specific" logic, it's best to put it in the subclass.
Reed Copsey
@Reed - Ideally we would live in an ideal word. :)
ChaosPandion
@ChaosPandion: Very true - and there are times to do this, but it's something that should be avoided when possible... Just thought I'd throw that out there :)
Reed Copsey
@Reed - I understand completely, in fact if I know that time constraints will lead to ineffectual use of polymorphism I will strive for a more simplistic functional approach.
ChaosPandion
+1  A: 

I would not do an enum for an EventType, if your subclass is going to be EventTypes. Enums are good for a fixed set of options - in your case, you want the flexibility of inheritance, so just use subclassing directly.

If it's just a matter of description, I would do something like:

public abstract class Event
{
    public string Description { get; private set;}
    public DateTime Time { get; protected set; }

    protected Event(string description, DateTime time) {
        this.Description = description;
        Time = time;
    }
}

This just lets your subclasses specify this for you, and it sounds like that is what you're after anyways.

Reed Copsey