gpt4 book ai didi

java - 避免代码重复——最好的方法

转载 作者:搜寻专家 更新时间:2023-10-31 08:23:25 24 4
gpt4 key购买 nike

我有两个方法,它们具有相同的列表和参数类型以及几乎相同的主体,但每个方法都调用另一个函数来获取元素列表。更准确地说:



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)
}

在这种情况下,避免代码重复的最佳方法是什么?我考虑过策略模式,但参数列表存在差异。

更新:



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)
}

所以有些变量是局部的,有些是通过参数传递的。

最佳答案

将它们分解为其他方法。

public void method1 (int a, int b) {
MyClass myClass = method3(a, b);
List<SomeObject> list = service.getListA(myClass.getC(), myClass.getD());
method4(list);
}

public void method2 (int a, int b) {
MyClass myClass = method3(a, b);
List<SomeObject> list = service.getListB(myClass.getC(), myClass.getD(), myClass.getE());
method4(list);
}

public MyClass {
private final int c;
private final int d;
private final int e;
...
}

public MyClass method3(int a, int b) {
// body
return new MyClass(c, d, e)
}

public void method4(List<SomeObject> list) {
// rest of body
}

关于java - 避免代码重复——最好的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14369405/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com