重構第二天:移動方法

來源:互聯網
上載者:User

標籤:style   class   blog   code   http   color   

原文地址:http://www.refactoring.com/catalog/moveMethod.html

在類A中,當一個方法正在用,或者將要用到的功能和資源大部分存在於另一個類B中,而非A類中時,這時我們要考慮把這個方法移到B類中去。

 

舉一個例子:

 1 class Project { 2   Person[] participants; 3 } 4  5 class Person { 6   int id; 7   boolean participate(Project p) { 8     for(int i=0; i<p.participants.length; i++) { 9       if (p.participants[i].id == id) return(true);10     }11     return(false);12   }   13 }14 15 ... if (x.participate(p)) ...

上面的例子中participate方法用到的都是Project類中的欄位,所以我們決定把participate()方法移到Project類中。

移動participate方法後:

 1 class Project { 2   Person[] participants; 3   boolean participate(Person x) { 4     for(int i=0; i<participants.length; i++) { 5       if (participants[i].id == x.id) return(true); 6     } 7     return(false); 8   }    9 }10 11 class Person {12   int id;13 }14 15 ... if (p.participate(x)) ...

這樣做後,使得每個類的職責更加明確,清晰。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.