55502f40dc8b7c769880b10874abc9d0

I have a very long method, monster(), and I want to skeletonize it by separating tasks.
In monster(), there is a part about handling the dragon. I want to refactor that piece of code out of the method to a new method called handleDragon() 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?

// Original method

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

// candidate for extraction
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; // ?
}

Refactorings

No refactoring yet !

Ee0505bbd355292778077fb662c88f13

Fu86

June 28, 2010, June 28, 2010 22:05, permalink

No rating. Login to rate!
int monster() {
    int rc = 0;
    int dragonRes;

    // some statements ...
    if (dragonRes = handleDragon()) return dragonRes;
    // rest of long method...

    return rc;
}
58629741b19b6b77523e15c1f0879dec

Marnie

April 24, 2011, April 24, 2011 00:02, permalink

No rating. Login to rate!

Walking in the presence of giants here. Cool thinking all aornud!

Walking in the presence of giants here. Cool thinking all aornud!
58629741b19b6b77523e15c1f0879dec

Marnie

April 24, 2011, April 24, 2011 00:02, permalink

No rating. Login to rate!

Walking in the presence of giants here. Cool thinking all aornud!

Walking in the presence of giants here. Cool thinking all aornud!

Your refactoring





Format Copy from initial code

or Cancel