I have two classes which represent a special kind of numeric value. Let’s call one “Value” and one “Fraction”; Fraction consists of a numerator and denominator of type Value. Because these are numeric values, operator overloading (+ – * /) makes a lot of sense. Given the nature of Value, division returns a Fraction. Operations can be performed with a mix of Values and Fractions.
Currently, I have just defined an implicit cast operator from Value to Fraction (and an explicit one from Fraction to Value, although I’m not using it), and am not using any sort of inheritance.
I am wondering if there is any “elegant” way to define both in terms of an abstract base class that defines the set of operations that are available, and calls the appropriate operation. Efficiency is a concern. I’d rather only use Fraction when necessary, and would rather not have to define more complex operations for both cases separately when they can be expressed using the same syntax.
One way I can see is doing something like the following for each operation, but I’m wondering if there are any better ways to do this?
public static AbstractValue operator *(AbstractValue a, AbstractValue b)
{
Value valA = a as Value;
Value valB = b as Value;
if(valA == null)
{
Fraction fractA = a as Fraction;
if(valB == null)
{
Fraction fractB = b as Fraction;
return fractA * fractB;
}
return fractA * valB;
}
if(valB == null)
{
Fraction fractB = b as Fraction;
return valA * fractB;
}
return valA * valB;
}
If your base class has to do things like trying to cast to a sub type and checking if it worked, this is a sign that the base class should not being implementing this method. In theory, the base class should have no knowledge of any specific child classes.
With your proposed implementation, if you want to add another child class, you will need to go and edit the base class. The whole point of inheritance is that you can add new types without having to edit the existing objects.