Video in progress

How do you protect architecture rules (layers, package dependencies) automatically, without trusting code review?

With ArchUnit tests: I write the allowed directions between layers, the absence of cycles and naming rules as ordinary JUnit tests. They run in CI, and when a rule is broken the build fails.

📖 Answer

Code review can't protect architecture over the long term: people get tired, new hires don't know the rules, "temporary" imports stay. You have to turn the rule into a test.

@AnalyzeClasses(packages = "com.shop")
class ArchitectureTest {

    @ArchTest
    static final ArchRule domainIsPure = noClasses()
        .that().resideInAPackage("..domain..")
        .should().dependOnClassesThat()
        .resideInAnyPackage("org.springframework..", "jakarta.persistence..", "..adapter..");

    @ArchTest
    static final ArchRule noCycles = slices()
        .matching("com.shop.(*)..")
        .should().beFreeOfCycles();

    @ArchTest
    static final ArchRule layers = layeredArchitecture().consideringAllDependencies()
        .layer("Web").definedBy("..adapter.in.web..")
        .layer("App").definedBy("..application..")
        .layer("Domain").definedBy("..domain..")
        .whereLayer("Web").mayNotBeAccessedByAnyLayer()
        .whereLayer("App").mayOnlyBeAccessedByLayers("Web");
}

Introducing it in legacy code: if you turn on every rule at once, you get hundreds of violations. ArchUnit's FreezingArchRule records the current violations and only reports new ones as errors. That way the debt doesn't grow, and it shrinks gradually.

Other tools:

  • Maven/Gradle multi-module: the hardest boundary, the compiler itself checks it;
  • Spring Modulith: checks module boundaries and generates documentation;
  • JPMS: strong for libraries, but rarely used in Spring applications.

Keep the number of rules small, but precise. 50 rules is a test nobody understands and that gets disabled every day.