views:

73

answers:

1

I have a number of classes that are all related conceptually, but some more-so at the details level than others. For example, these three classes have nearly identical properties (although member functions will vary):

public class RelatedA : IRelatedType
{
    public string Name { get; set; }
    public string Value { get; set; }
    public DateTime Stamp { get; set; }
}

public class RelatedB : IRelatedType
{
    public string Name { get; set; }
    public string Value { get; set; }
    public DateTime Stamp { get; set; }
}

public class RelatedC : IRelatedType
{
    public string Name { get; set; }
    public string Value { get; set; }
    public DateTime Stamp { get; set; }
    public int Special { get; set; }
}

There are a couple of other classes that are conceptually related to the above 3, but can be a bit different implementation-wise:

public class RelatedD : IRelatedType
{
    public string Name { get; set; }
    public string Statement { get; set; }
}

public class RelatedE : IRelatedType
{
    public string Name { get; set; }
    public string Statement { get; set; }
    public bool IsNew { get; set; }
}

Instances of these can be created by a factory based on some sort of "type" enumerated value. The problem is that later on when these objects are being used (in a business layer, for example), there could be a lot of code like this:

IRelatedType theObject = TheFactory.CreateObject(SomeEnum.SomeValue);

if (theObject is RelatedC)
{
    RelatedC cObject = theObject as RelatedC;
    specialVal = cObject.Special;
}
else if (theObject is RelatedD)
{
    RelatedD dObject = theObject as RelatedD;
    statementVal = dObject.Statement;
}
else if (theObject is RelatedE)
{
    RelatedE eObject = theObject as RelatedE;
    statementVal = eObject.Statement;
    isNewVal = eObject.IsNew;
}

This could be repeated in many places. Is there a better approach to the design that I should be using (there's got to be)?

+1  A: 

You could try and factor the differences into seperate classes that are then provided so for example:

IRelatedType theObject = TheFactory.CreateObject(SomeEnum.SomeValue);
RelatedTypeHelper theHelper=TheFactory.CreateHelper(theObject);
theHelper.DoSpecialThing(theObject);

Now you won't have to have all the if else blocks, and if you add a new type which requires new handling, you just whip up a new helper implement the required pieces and you should be good to go. The helper should help document this process.

I would also question why a single method would have such a different implementation for specialVal and StatementVal could be your sample, but It makes me curious what your really doing here. can you simplify things back taking a step back and questioning the point of these being included in this specific hierarchy.

JoshBerke