2010-04-26

Exit strategy: Single exit point is less readable

Single exit point produces the pyramid of code syndrome.

bool solve2
    (
        double a, double b, double c
        , double& x1, double& x2
    )
{
    bool ret = true;
    if(a!=0) {
        double det = b*b - 4*a*c;
        if(det>=0) {
            ret = true;
            det = sqrt(det);
            double p2a = 1 / (2*a);
            x1 = (-b - det) * p2a;
            x2 = (-b + det) * p2a;
            // The top of the code pyramid
        } else
            ret = false;
    } else
        ret = false;
    return ret;
}

Using early returns helps keeping the error handing and productive code apart.

bool solve2
    (
        double a, double b, double c
        , double& x1, double& x2
    )
{
    // Checking for trivial errors and trivial solutions
    if(a==0)
        return false;
    double det = b*b - 4*a*c;
    if(det<0)
        return false;
    // Main part without pyramid
    det = sqrt(det);
    double p2a = 1 / (2*a);
    x1 = (-b - det) * p2a;
    x2 = (-b + det) * p2a;
    return true;
}

Note: This function solves the quadratic equation (a * x^2 + b * x + c = 0).

Note: You have to be careful with the multiple exit point style if you are acquiring resources (opening files, allocating memory, ...), because it can lead to leaks. Avoiding these kind of leaks is simpler in C++ than in most languages, because the lifetime of acquisitions can be bound to scope.

No comments:

Post a Comment