Refactoring - Replacing Conditionals with State
Posted: Oct 5, 2004 10:52 PM
Advertisement
I'm currently working my way through Joshua Kerievsky's book "Refactoring to Patterns". I've started using one of the refactorings - "Replace State-Altering Conditionals with State" (p166) - on some legacy code I'm updating. Step one - replace the state field with a state class - no problem. Step two - create a subclass of the state class for each state and use them to in place of the state class - again no problem. Step three - move all methods that alter states into the state class - Yep, no problem. Step four - copy any methods that alter from state A to B into state sub class A, and remove all state conditional code - Ah, problem! I see the logic but (think I) also see a flaw. In the example given (p176) the following method:public void claimedby(SystemAdmin admin, SystemPermission permission)
{
if (!permission.getState().equals(REQUESTED)
&& permission.getState().equals(UNIX_REQUESTED))
return ;
permission.willBeHandledBy(admin);
if (permission.getState().equals(REQUESTED))
permission.setState(CLAIMED);
else if (permission.getState().equals(UNIX_REQUESTED))
permission.setState(UNIX_CLAIMED);
}
is moved to the state subclass PermissionRequested and simplified to:public void claimedby(SystemAdmin admin, SystemPermission permission)
{
permission.willBeHandledBy(admin);
permission.setState(CLAIMED);
}
on the basis that, in that subclass, getState will always return REQUESTED. The fly in the ointment is "What if that innocuous method in the middle (willBeHandledBy) alters the state?" This happens in my code and since the conditional state checking logic has been removed then the code flow has been changed and we no longer have a code refactoring but a logic modification. Has anyone else read this book? Have I missed something here? Vince.