[英]Eclipse method call refactoring
我正在嘗試以以下模式重構一些代碼:
// from
object1.foo(object2).bar() ;
// to
fooBar(object1, object2) ;
哪里
對於上下文,更改是由於foo()在某些情況下返回null所致,這在調用bar()時導致NullPointerExceptions。
fooBar()首先檢查foo()是否會返回null,如果是則返回默認值,否則調用bar()並返回它。
我正在使用Eclipse,我想知道是否有一個很好的方法來執行此操作,而不是使用文件搜索中的正則表達式手動更改每次出現的情況。
編輯-有關評論的更多信息:
我無法控制foo()的實現。
關於object1是超類的子類:
//in some cases this happens
SuperClass object1 = new SuperClass(/*whatever*/) ;
//in other cases this happens
ChildClass object1 = new ChildClass (/*whatever*/) ;
我應該提一下,因為它可能會影響如何搜索object1。
之前和之后的代碼的[也許]更清晰的版本:
//before
Object result = object1.foo("a string").bar() ;
//NullPointerException if foo() returns null! :(
//after
Object result = fooBar(object1, "a string") ;
同時,在單獨的實用程序類中,存在:
public static Object fooBar(SuperClass obj, String str) {
Object result = DEFAULT_RESULT ;
if (obj != null && str != null && obj.fooAble(str)) {
result = obj.foo(str).bar() ;
}
return result ;
}
我發現解決方案甚至花了我這三年的時間! :)
實際上,基於代碼重構的解決方案將一個方法調用替換為另一個方法調用。 示例:在擁有之前: obj1.method1(){};
obj2.method2(obj1){ obj1.method1(); };
在應用eclipse重構“ Inline ...”之后,我們將調用obj2.method2(obj1);
替換為調用obj1.method1();
因此,對於您的情況:
object1.foo(object2)
任何調用再次應用“ Inline ...”,該調用將所有此類調用替換為fooBar(this,object2);
而已!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.