Potential solution to code duplication

Coordinator
Apr 17, 2011 at 9:56 AM

Hi All,

I have been searching for a solution to the code duplication problem - i.e that we have to copy and paste code for each different arithmetic type (double, float, int etc.), because it will become a real nuisance if we have to maintain numerous copies of the same algorithm.

It looks like there is a fairly neat solution here: http://www.lambda-computing.com/publications/articles/generics2/

The principle is that we have a "Calculator" that knows how to perform the arithmetic operations for a particular type.  This implements an "ICalculator" interface that defines what the basic operations are.  So we create a calculator for each basic type that is supported and then use the functions on that calculator instead of using the operators directly, which means that we can pass the calculator as a Generic parameter and have one Generic version of each function.  The trick is to create each calculator as a struct rather than a class so that the arithmetic function calls are inlined and there is no extra overhead.

I'm going to try this out on one of the math functions and if it looks like a good solution, I'll post an explanation of what I've done.

Jeremy.

Coordinator
Apr 17, 2011 at 4:36 PM

Hi All,

I have applied this approach to the unwrap function (see Complex.cs) and it seems to work very well.  There is a single implementation of the unwrap functionality in a generic method, which takes two type parameters (one for the basic type and one for the calculator used to operate on it).  Each overload is then created as a separate one-liner method that just calls the generic method with the right calculator type (this hides the calculator from the library user).

The only drawback with this approach is that the code that does the arithmetic is a bit less clear because of calling functions instead of using operators, but I think that is a small price to pay for having one copy of the implementation.

The "INumber" interface can be extended as required to include any other math functions that need to be called with a generic type.

Please take a look in Complex.cs at the unwrap function and let me know what you think about this approach.

Cheers

Jeremy.