C # - Designing classes using inheritance and operator overloading

I have two classes that are a special kind of numeric value. Let me call one "value" and "fraction"; A fraction consists of a numerator and a denominator of type Value. Since these are numerical values, operator overloading (+ - * /) makes a lot of sense. Given the nature of the value, division returns a fraction. Operations can be performed using a combination of values โ€‹โ€‹and fractions.

Currently, I just defined an implicit transfer operator from Value to Fraction (and explicit from Fraction to Value, although I don't use it), and I don't use any inheritance.

I am wondering if there is any โ€œelegantโ€ way to define both in terms of the abstract base class, which defines the set of available operations, and invokes the corresponding operation. Efficiency is a problem. I would prefer to use Fraction only when necessary, and it would not be necessary to define more complex operations for both cases separately, if they can be expressed using the same syntax.

One way that I see is to do something like the following for each operation, but I wonder if there are any more efficient 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; } 
+3
source share
2 answers

If your base class should do things such as trying to apply to a subtype and check if it works, this is a sign that the base class should not use this method. Theoretically, the base class should not know any specific child classes.

With the proposed implementation, if you want to add another child class, you will need to go over and edit the base class. The whole nature is that you can add new types without having to edit existing objects.

+1
source

Actually, I would see the most "elegant" way of defining each option separately.

Benefits:

  • Choosing the right calculation is done by the compiler at compile time (where it should be done), and not at run time.
  • Each calculation method contains only a calculation code.

Disadvantages:

  • This is a bit more code (just learn frigging)

So let's see you have:

  • Fraction about fraction
  • Fraction value
  • The value of the op fraction
  • Value op value

Times 4 operations, giving a total of only 16 methods, which are likely to be on approximately one line.

+1
source

All Articles