我有两个方法具有相同的参数列表和类型几乎相同的主体,但他们每个都调用另一个函数来获取元素列表。更确切地说:避免代码重复 - 最佳方法
public void method1 (int a, int b) {
//body (the same in both of methods)
List<SomeObject> list = service.getListA(int c, int d);
//rest of the body (the same in both of methods)
}
public void method2 (int a, int b) {
//body (the same in both of methods)
List<SomeObject> list = service.getListB(int c, int d, int e);
//rest of the body (the same in both of methods)
}
这种情况下避免代码重复的最佳方法是什么?我想到了Strategy模式,但是参数列表中存在差异的问题。
UPDATE:
public void method1 (int a, int b) {
//body (the same in both of methods)
int c = some_value;
List<SomeObject> list = service.getListA(a, b, c);
//rest of the body (the same in both of methods)
}
public void method2 (int a, int b) {
//body (the same in both of methods)
int c = some_value;
int d = another_value;
List<SomeObject> list = service.getListB(a, b, c, d);
//rest of the body (the same in both of methods)
}
所以有些变量是局部的,有些是通过参数传递。
通过你'列出'作为一个参数的单个函数并包装它? –
fge
c,d和e字段还是它们在这些方法中的局部变量? –
你可以重写你的例子,以便编译或至少使用正确的语法吗? –