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

Luk*_*cki 5 java design-patterns

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



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

Run Code Online (Sandbox Code Playgroud)

在这种情况下,避免代码重复的问题的最佳方法是什么?我想到了战略模式,但是参数列表存在差异.

更新:



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

Run Code Online (Sandbox Code Playgroud)

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

Ale*_*rlo 6

将它们分解为其他方法.

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
}
Run Code Online (Sandbox Code Playgroud)

  • 仍然会有代码重复,调用这两种方法就是代码重复本身......我认为OP是在设计模式方法之后. (5认同)