方法和构造函数<! - ? - >都从Member继承,两者都有getExceptionTypes()方法。如何在这种情况下避免代码重复?

时间:2011-09-22 14:39:43

标签: java oop refactoring code-duplication

我在我的代码库中有这两种方法,我想以某种方式合并以避免代码重复:

protected IJavaType[] getExceptionTypes(Method method) {
    Class<?>[] declaredExceptions = method.getExceptionTypes();

    IJavaType[] exceptions = new IJavaType[declaredExceptions.length];

    for (int i = 0; i < declaredExceptions.length; i++) {
        exceptions[i] = getType(declaredExceptions[i]);
    }

    return exceptions;
}

protected IJavaType[] getExceptionTypes(Constructor<?> c) {
    Class<?>[] declaredExceptions = c.getExceptionTypes();

    IJavaType[] exceptions = new IJavaType[declaredExceptions.length];

    for (int i = 0; i < declaredExceptions.length; i++) {
        exceptions[i] = getType(declaredExceptions[i]);
    }

    return exceptions;
}

有没有办法分解代码重复(除了使用带有模板模式的子类)?

2 个答案:

答案 0 :(得分:3)

简单地说:

private IJavaType[] getExceptionTypes(Class<?>[] declaredExceptions) {
    IJavaType[] exceptions = new IJavaType[declaredExceptions.length];

    for (int i = 0; i < declaredExceptions.length; i++) {
        exceptions[i] = getType(declaredExceptions[i]);
    }

    return exceptions;
}

protected IJavaType[] getExceptionTypes(Method method) {
    return getExceptionTypes(method.getExceptionTypes());
}

protected IJavaType[] getExceptionTypes(Constructor<?> c) {
    return getExceptionTypes(c.getExceptionTypes());
}

答案 1 :(得分:2)

你可以很容易地提取大部分

protected IJavaType[] getExceptionTypes(Method method) {
    return getExceptionTypesImpl(method.getExceptionTypes());
}

protected IJavaType[] getExceptionTypes(Constructor<?> c) {
    return getExceptionTypesImpl(c.getExceptionTypes());    
}

private void getExceptionTypesImpl(Class<?>[] declaredExceptions) {
    IJavaType[] exceptions = new IJavaType[declaredExceptions.length];

    for (int i = 0; i < declaredExceptions.length; i++) {
        exceptions[i] = getType(declaredExceptions[i]);
    }

    return exceptions;
}