Bad taste of code 01: repeated code (duplicated code)

Source: Internet
Author: User

If you see the sameProgramStructure, then you can be certain: try to combine them into one, and the program will become better.

 

The two functions of the same class contain the same expression.Extract Method(Extraction function)ExtractDuplicateCodeAnd then let the two locations call the extracted code.

 

The two sibling child classes contain the same expression. Extract Method(Extraction function)And then use the extracted FunctionsPull up Method(Method move up)To push it into the superclass. If

It's just similar, not exactly the same, so you have to useExtract Method (Extraction function) Separate the similarity and difference parts to form a separate function. Then you may find that you can useForm template method(Create a template function) Obtain a template method design pattern. If some functions use different Algorithm To do the same thing, you can select one of them clearly and use Substitute Algorithm(Replacement algorithm) Replace the algorithms of other functions.

If two irrelevant classes have repeated code, you should consider using one of them. extract class , Duplicate code is extracted into an independent class, and then this new class is used in another class. However, the function where repeated code is located may only belong to a class, and the other class can only call it, or this function may belong to the third class, the other two classes should reference the third class. You must decide where the function is most suitable and ensure that it will not appear anywhere else after it is placed.

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.