Search code examples
javaooprefactoringcode-duplication

Method and Constructor<?> both inherit from Member, both having a getExceptionTypes() method. How to avoid code duplication in this scenario?


I have both these methods in my code base, which I'd like to merge in some way to avoid 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;
}

Is there any way to factor out the code repetition (other than using subclassing with template pattern)?


Solution

  • How about simply:

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