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)
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 },
...
};
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With