zoukankan      html  css  js  c++  java
  • 重构第二天:移动方法

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

    在类A中,当一个方法正在用,或者将要用到的功能和资源大部分存在于另一个类B中,而非A类中时,这时我们要考虑把这个方法移到B类中去。

    image

    举一个例子:

     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)) ...

    这样做后,使得每个类的职责更加明确,清晰。

  • 相关阅读:
    HOWTO get multiple value from the same name checkbox elements or radiobution elements
    你家有几台电脑
    *qian翻
    nginx 域名绑定
    linode设置汇总
    how to relize 301 redirect on bottle
    Nginx禁止未在服务器绑定的域名访问
    linode设置汇总
    sogouq免费企邮
    linode设置汇总
  • 原文地址:https://www.cnblogs.com/peteryan/p/3805792.html
Copyright © 2011-2022 走看看