避免複製與貼上

2021-09-05 06:33:21 字數 2138 閱讀 4294

《重構之美》之一

在我的程式設計生涯中,碰到類似copy-paste的情況簡直不勝列舉。在一次專案中,我們對開源專案jasper report進行了擴充套件。我們加入了對新報表型別(cjt_report)的支援。在reportparameteraction類中,我們需要對報表物件reportunit判斷報表型別。於是,我在reportparameteraction類中定義了如下的私有方法: 

privatevoidsetreportunittypebyfileresource(reportunit reportunit)else

}      }

protected

reportunit reportunit = loadreportunit(context);

setreportunittypebyfileresource(reportunit);

initialrequestcontext(context, reportunit);

intreporttype = reportunit.getreporttype();

if(reporttype == reportunit.

cjt_report)

//…… 

}

後來,我發現在engineserviceimpl類中同樣需要判斷報表的型別。然而,setreportunittypebyfileresource()方法卻被定義為reportparameteraction的私有方法,無法被engineserviceimpl物件呼叫。最簡單的做法是採用複製的方式,將這段**複製到engineserviceimpl中。好了,如果此時我們不能忍住copy-paste的簡便所帶來的**,或許就會陷入重複的泥沼了。copy的動作絕對應該鳴起刺耳的警聲。我們需要對這一做法保持足夠的警惕。

通過分析setreportunittypebyfileresource()方法,我發現該方法需要操作的物件均與reportunit有關,而本身該方法的職責就是要獲得reportunit的型別,並對其欄位reporttype進行設定,因此,完全可以將它搬移到reportunit中(move method重構,不是嗎?)。由於reportunit已經增加了對reporttype欄位的get和set訪問方法,我發現它們與我要重構的方法實有異曲同工之處,因而決定將其搬移到getreporttype()方法中: 

publicintgetreporttype()

returngetreporttypebyfileresource();

} privateintgetreporttypebyfileresource() }

} }

returnreporttype; }

privatebooleanhasreporttypebeenset()else}

注意,在以上過程中,除了使用move method之外,我還運用了rename method以及extract method等重構手法。

protected

reportunit reportunit = loadreportunit(context);

setreportunittypebyfileresource(reportunit);

initialrequestcontext(context, reportunit);

intreporttype = reportunit.getreporttype();

if(reporttype == reportunit.

cjt_report)

//…… 

}

避免複製與貼上

重構之美 之一 在我的程式設計生涯中,碰到類似copy paste的情況簡直不勝列舉。在一次專案中,我們對開源專案jasper report進行了擴充套件。我們加入了對新報表型別 cjt report 的支援。在reportparameteraction類中,我們需要對報表物件reportunit判...

複製與貼上

我們用文字處理器來處理乙個特殊的文字檔案,該文字檔案共有n行文字,每一行文字僅包含乙個自然數,第一行為1 第二行為2,以此類推至n行為自然數n。編寫乙個程式求出在進行了連續若干次 剪下和貼上 操作後,文字檔案中前十行的內容。輸入檔案的第一行包含兩個用空格隔開的自然數n和k,n表示檔案的總行數 10 ...

貼上複製Android複製和貼上的實現

最近研究貼上複製,稍微總結一下,以後繼續補充 main.xml如下 mainactivity如下 每日一道理 漫漫人生路,誰都難免會遭遇各種失意或厄運。在淒風苦雨 慘霧愁雲的考驗面前,乙個強者,是不會向命運低頭的。風再冷,不會永遠不息 霧再濃,不會經久不散。風息霧散,仍是陽光燦爛。package c...