I am working with some old C# code at the moment, which basically uses derived types for the sole purpose of using the Type as a ‘property’, such as:
public abstract class Fruit
{
public int Property { get; set; }
}
public class Apple : Fruit {}
public class Pear : Fruit {}
And then:
public void Foo(Fruit item)
{
if(item is Apple)
{
// do something
return;
}
if(item is Pear)
{
// do something
return;
}
throw new ArgumentOutOfRangeException("item");
}
I would have included an enum property on BaseClass to specify the ‘type’:
public class Fruit
{
public int Property { get; set; }
public FruitType Type { get; set; }
}
public enum FruitType
{
Apple,
Pear
}
and then used it thus:
public void Foo(Fruit item)
{
switch(item.Type)
{
case FruitType.Apple:
// do something
break;
case FruitType.Pear:
// do something
break;
default:
throw new ArgumentOutOfRangeException();
}
}
I feel that the former pattern is a misuse of inheritence, but are there any advantages to it that I should consider before re-writing this code?
The standard “OO” way to deal with this situation is to make DoSomething an abstract method on Fruit. Then the caller just calls DoSomething, knowing that the implementation will do the right thing.
The downside of this approach is that it puts responsibility for working out all possible “somethings” that a user might possibly want onto the author of the abstract class.
That downside can be mitigated by using the “visitor pattern”. The visitor pattern is a standard way to enable third parties to efficiently switch behaviours based on the runtime type of a value. You might consider researching it.
Your second approach — discriminating the type with a tag — is quite common and can be very efficient. Roslyn uses this technique extensively. It is considered by OO purists to be a bit smelly, but fortunately I am not an OO purist.
A variation on your second technique that I like is:
Now the only way that a Fruit user can determine the type is through the tag, because Apple and Orange are not accessible. You know that no third party is going to make their own Fruit because the only Fruit constructor is private.