本文紧接
使用重构移除丑陋的if else代码(1)。
使用Enum替换int常量
这一步比较简单,先创建一个enum类:
package de.jingge.refactoring;
public enum SystemState {
    LOGGEDIN,
    LOGGEDOUT,
    IDLE;
}
然后开始重构SystemManager, 使用SystemState代替SystemManager里的int状态:
   1. 添加 import static de.jingge.refactoring.SystemState.*;
   2. 删除所有的integer常量   
   3. 将变量state的类型改为SystemState.
代码如下:
package de.jingge.refactoring;
import static de.jingge.refactoring.SystemState.*;
public class SystemManager {
    SystemState state;
    public void login() {
        // call service#login()
        updateState(LOGGEDIN);
    }
   
    public void logout() {
        // call service#logout()
        updateState(LOGGEDOUT);
    }
   
    public void idle() {
        // call some other services
        updateState(IDLE);
    }
   
    public void updateState(SystemState state) {
        if (state == LOGGEDIN) {
            // do something after logging in is successful,
            // for example: show welcome dialog, open the last edit document, etc.
        } else if (state == LOGGEDOUT) {
            // do something after logging out is successful,
            // for example: free used resource, dispose GUI components, etc.
        } else if (state == IDLE) {
            // do something after the user is idle,
            // for example: save the application state temporarily, lock the application, etc.
        } else {
            throw new IllegalArgumentException("unknown state");
        }
        this.state = state;
    }
}
然后重构测试类:
1.    添加import static de.jingge.refactoring.SystemState.*;
2.    删除所有常量前引用的SystemManager.
package de.jingge.refactoring;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import static de.jingge.refactoring.SystemState.*;
public class SystemManagerTest {
    private static SystemManager manager;
    @BeforeClass
    public static void setUpClass() throws Exception {
        manager = new SystemManager();
        // add some service mock objects
    }
   
    @AfterClass
    public static void tearDownClass() throws Exception {
    }
   
    @Test
    public void login() {
        manager.login();
        assertEquals(manager.state, LOGGEDIN);
    }
  
    @Test
    public void logout() {
        manager.logout();
        assertEquals(manager.state, LOGGEDOUT);
    }
    @Test
    public void idle() {
        manager.idle();
        assertEquals(manager.state, IDLE);
    }
}
运行这个测试类->通过
下一篇文章
使用重构移除丑陋的if else代码(3)开始处理if else hell
声明:本文版权归作者所有,如需转载请注明出处。