Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return statements when doing Extract Method

Let's say you have a very long method, like this:

int monster()
{
    int rc = 0;

    // some statements ...

    if (dragonSlayer.on_vacation()) {
        cout << "We are screwed!\n";
        if (callTheKing() == true)
            return 1;
        else
            return 2;
    } else {
        cout << "We are saved!\n";
        slayTheDragon();
    }

    // rest of long method...

    return rc;
}

and I'm working on skeletonizing the code. I want to extract the dragon slaying part to

int handleDragon() {
    if (dragonSlayer.on_vacation()) {
        cout << "We are screwed!\n";
        if (callTheKing() == true)
            return 1;
        else
            return 2;
    } else {
        cout << "We are saved!\n";
        slayTheDragon();
    }

    return 0; // ?
}

and replace the code in monster() with a call to handleDragon().

But there is a problem. There is a return statement in the middle of that part. If I keep the part where the return code of handleDragon() is handled, it will keep the litter in the big method.

Besides using exceptions, is there an elegant and safe way to refactor this piece of code out of the monster method? How should these types of situations be handled?

like image 701
Michael Avatar asked Sep 23 '26 05:09

Michael


1 Answers

Return 0 from the handleDragon method if the dragon slayer is available:

int handleDragon() {
    if (dragonSlayer.on_vacation()) {
        cout << "We are screwed!\n";
        if (callTheKing() == true)
            return 1;
        else
            return 2;
    } else {
        cout << "We are saved!\n";
        slayTheDragon();
        return 0;
    }
}

Then back in the monster method, if the return value was greater than zero, return that value, otherwise carry on:

// some statements ...

int handleDragonResult = handleDragon();
if (handleDragonResult > 0) {
    return handleDragonResult;
}

// rest of long method...

You should also document the handleDragon method, to explain the value that gets returned.

like image 184
Richard Fearn Avatar answered Sep 24 '26 23:09

Richard Fearn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!