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.