Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch values between two parameters [Best Practice / Better Code]

I bet this task has a shorter and more nice way to be written?

/// <summary>
/// Consumption between two parameters
/// </summary>
public double Consumed(double val1, double val2)
{
    double currentValue = 0;

    // Don't calculate backward
    if (val1 < val2)
    {
        currentValue = val1;
        val2 = val1;
        val2 = currentValue;
    }
    currentValue = (val1 - val2);
    return currentValue;
}

One way would just be invert result if negative. What would you say state as "Best practice"? Thank's in advanced,

like image 555
Independent Avatar asked Dec 17 '22 09:12

Independent


2 Answers

You're calculating the absolute value of the difference between the two input values:

public double Consumed(double val1, double val2)
{
    return Math.Abs(val1 - val2);
}
like image 123
dtb Avatar answered May 15 '23 21:05

dtb


I usually just call my function again with the parameters swapped:

public double Consumed(double val1, double val2)
{
    if (val1 < val2)
        return Consumed(val2,val1);

    //Do Stuff
}

Of course in your example Math.Abs already exists, but for the general case this is my preferred solution.

like image 35
CodesInChaos Avatar answered May 15 '23 21:05

CodesInChaos