// 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 !
Fu86
June 28, 2010, June 28, 2010 22:05, permalink
int monster() {
int rc = 0;
int dragonRes;
// some statements ...
if (dragonRes = handleDragon()) return dragonRes;
// rest of long method...
return rc;
}
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?