Duplicated Code

来源:互联网 发布:淘宝手机主板可靠吗 编辑:程序博客网 时间:2024/04/30 12:15

If you see the same code structure in more than one place, you can be sure that your program will be better if you find a way to unify them.

1. The simplest duplicated code problem is when you have the same expression in two methods of the same class.
Extract Method

2. Another common duplicated code problem is when you have the same expression in two sibling subclasses.
Extract Method in both classes then Pull UP Field.
If the code is similar but not the same, you need to use
Extract Method to separate the similar bits from the different bits. You may then find you can use Form Template Method. If the methods do the same thing with a different algorithm, you can choose the clearer of the two algorithms and use Substitute Algorithm.

3. If you have duplicated code in two unrelated classes, consider using
Extract Class in one class and then use the new component in the other. Another possibility is that the method really belongs only in one of the classes and should be invoked by the other class or that the method belongs in a third class that should be referred to by both of the original classess.