The Artima Developer Community
Sponsored Link

Java Answers Forum
Refactoring - Replacing Conditionals with State

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Vincent O'Sullivan

Posts: 724
Nickname: vincent
Registered: Nov, 2002

Refactoring - Replacing Conditionals with State Posted: Oct 5, 2004 10:52 PM
Reply to this message Reply
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.

Topic: Using Recursion Previous Topic   Next Topic Topic: write to a file in applet

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use