clarkware / jdepend

A Java package dependency analyzer that generates design quality metrics.
MIT License
655 stars 133 forks source link

ClassFileParser made extensible #2

Closed vpeurala closed 14 years ago

vpeurala commented 14 years ago

Hello, in my project there is a need to analyze dependencies between individual classes, instead of just packages (as supported by JDepend). To achieve this, we need to make ClassFileParser extensible so that we can handle the found imports in our own way. Here is an example subclass of ClassFileParser (this does not compile with JDepend HEAD version, only with my changes):

public class ClassDependencyAwareParser extends ClassFileParser {
    @Override
    protected JavaClass newJavaClass() {
        return new ClassDependencyAwareJavaClass("Unknown");
    }

    // ...         

    @Override
    protected void addClassConstantReferences() throws IOException {
        for (int j = 1; j < constantPool.length; j++) {
            if (constantPool[j].getTag() == CONSTANT_CLASS) {
                String name = toUTF8(constantPool[j].getNameIndex());
                addImport(getPackageName(name), name);
                debug("Parser: class type = " + slashesToDots(name));
            }
            if (constantPool[j].getTag() == CONSTANT_DOUBLE || constantPool[j].getTag() == CONSTANT_LONG) {
                j++;
            }
        }
    }

    protected void addImport(final String importPackage, final String importedClass) {
        if (importPackage != null && getFilter().accept(importPackage)) {
            jClass.addImportedPackage(new JavaPackage(importPackage));
        }
        ((ClassDependencyAwareJavaClass) jClass).addImportedClass(importedClass);
    }
}

I have changed most of the private stuff in ClassFileParser to protected so that subclasses can override some of the behavior.

It would be very nice if you could include these commits in JDepend itself. They cannot break any existing functionality, because I have only made stuff more visible and added hook method newJavaClass(). No actual logic is changed.

Best regards, Ville Peurala

pascallouisperez commented 14 years ago

I'd be personally against such changes in JDepend. In proper OO, you don't extend to adapt behavior, you delegate. I'd recommend adapting the changes to use the visitor pattern.