Refactoring the next day: moving methods

Source: Internet
Author: User

Original Address: http://www.refactoring.com/catalog/moveMethod.html

In Class A, when a method is in use, or the functionality and resources that will be used are mostly present in another class B, rather than in Class A, then we need to consider moving this method to Class B.

To give an example:

1 classProject {2 person[] participants;3 }4 5 classPerson {6   intID;7 Boolean participate (Project p) {8      for(intI=0; i<p.participants.length; i++) {9       if(p.participants[i].id = = ID)return(true);Ten     } One     return(false); A   }    - } -  the...if(X.participate (p)) ...

In the example above, the participate method uses fields from the project class, so we decided to move the participate () method to the Project class.

After moving the participate method:

1 classProject {2 person[] participants;3 Boolean participate (Person X) {4      for(intI=0; i<participants.length; i++) {5       if(participants[i].id = = x.id)return(true);6     }7     return(false);8   }   9 }Ten  One classPerson { A   intID; - } -  the...if(P.participate (x)) ...

By doing so, the responsibilities of each class are made clearer and clearer.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.