Java: Finding Package Cycles

JDepend is a tool for detecting cycles between your Java packages. It is often used from a Maven plugin to generate reports for the project's Maven site.
In most teams, however, people only look at these reports from time to time. So when a cycle has been introduced, it takes a while until someone notices. The later the cycle is detected, the harder it is to fix. Fortunately, there's an easy solution.

Using JDepend's API, you can add a cycle check to your unit tests. This way, cycles will be detected much earlier, when developers (or your continuous integration server) run the unit tests.

All you have to do is to add the following test (JUnit 4 syntax):

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import jdepend.framework.JDepend;
import org.junit.Test;

public class DependenciesTest {
    @Test
    public void testCycles() throws IOException {
        JDepend jdepend = new JDepend();
        jdepend.addDirectory("target/classes");

        jdepend.analyze();

        assertThat(jdepend.containsCycles(), is(false));
    }
}

If your project uses Maven, you have to add the following dependency:

<dependency>
    <groupId>jdepend</groupId>
    <artifactId>jdepend</artifactId>
    <version>2.9.1</version>
    <scope>test</scope>
</dependency>

When the test fails you can use a JDepend-based tool like the Eclipse plugin to pinpoint the exact problem.

If you want to detect cycles only on an application-specific level (for example between layers or modules) instead of the package level, you can define components as described in JDepend's API documentation.

social