开发者

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;
        v开发者_如何学运维al2 = 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,


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);
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜