前言
- 所謂重構(refactoring):
在不改變代碼外在行為的前提下,對代碼做出修改,以改進程序的內部結構。 – Martin Fowler - 背景
最近在做需求,需要對方法加權限控制,發現舊方法不再適用,需要重新抽象。積累了一個安全重構小技巧。
步驟
- 期望將 methodB 恢復到 methodA 和 methodC 中,刪掉methodB
public static void methodA() {System.out.println("methodA");System.out.println("doSomething before methodB");methodB();System.out.println("doSomething after methodB");}public static void methodC() {System.out.println("methodC");System.out.println("doSomething before methodB");methodB();System.out.println("doSomething after methodB");}public static void methodB() {System.out.println("doSomething while methodB");}public static void main(String[] args) {methodA();methodC();}
- idea 重構 。快捷鍵:Ctrl + Alt + N
- 好處
消除手工移動因素,重構動作較為安全。
后記
- 《修改代碼的藝術》
- 《重構》
以上兩本書,主要是在強調如何把代碼調整到易讀,代碼出現壞味道時如何修改。
idea 里面 “Refactor” 中的很多用途都有上述兩本書的影子。
如果決定要重構,除了需要有測試用例保證重構安全,還需要多使用工具消除人工移動代碼的隱患。