Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can operations be generalized?

Tags:

c#

I just wrote this code:

private double PerformOperation(OperationEnum operation, double aggregateValue, 
                                double sourceValue)
{
    if (operation == OperationEnum.Sum)
        return aggregateValue + sourceValue;
    if (operation == OperationEnum.Subtract)
        return aggregateValue - sourceValue;
    if (operation == OperationEnum.Multiply)
        return aggregateValue * sourceValue;
    if (operation == OperationEnum.Divide)
        return aggregateValue / sourceValue;
    throw new InvalidOperationException("Unsupported Aggregation Operation");
}

It seems very repetitive. Is there a way to generalize this? So I don't have to have 4 lines that are the same except a different sign?

(Note: if there is a better way that does not use the OperationEnum that is great)

like image 363
Vaccano Avatar asked Jan 21 '11 21:01

Vaccano


Video Answer


3 Answers

You can make a Dictionary<OperationEnum, Func<double, double, double>>:

static readonly Dictionary<OperationEnum, Func<double, double, double>> operations = 
    new Dictionary<OperationEnum, Func<double, double, double>> {
        { OperationEnum.Sum, (a, b) => a + b },
        ...
    };
like image 159
SLaks Avatar answered Sep 29 '22 10:09

SLaks


It looks about right to me, although I'd use a switch statement for this. But maybe I don't understand what you're trying to do?

switch(operation)
{
    case OperationEnum.Sum:      return aggregateValue + sourceValue;
    case OperationEnum.Subtract: return aggregateValue - sourceValue;
    case OperationEnum.Multiply: return aggregateValue * sourceValue;
    case OperationEnum.Divide:   return aggregateValue / sourceValue;
    default:
        throw new InvalidOperationException("Unsupported Aggregation Operation");
}

It's essentially the same, but at least it looks prettier.

like image 21
Justin Morgan Avatar answered Sep 29 '22 10:09

Justin Morgan


You can create a dictionary of delegates, so your function will look something like:

private double PerformOperation(OperationEnum operation, double aggregateValue, 
                            double sourceValue)
{
    return operators[operation](aggregateValue, sourceValue);
}
like image 24
Elalfer Avatar answered Sep 29 '22 09:09

Elalfer