There are a bunch of tools that help in delivering a better, cleaner code. I guess most of us use Sonar for the static analysis of the code. That is awesome, especially if we integrate that with the build process or at least with the Jenkins pipeline for our development branch. Just to fail the pull request once the code does not meet a quality gate or introduces new issues. Can we go further with the fast feedback? Sure, we can configure SpotBugs (FindBugs) to support Sonar with finding subtle bugs and code smells or Checkstyle to validate whether the code adheres to established coding standards. Furthermore, Modernizer can detect uses of legacy APIs which modern Java versions supersede. But how about other aspects, like proper relations between classes and dependencies of packages, cyclic dependencies, project-specific naming conventions, and the overall established code architecture? The ArchUnit comes to the rescue!
My story with the ArchUnit
Usually, I attach several tools to check the code quality to projects I work on. All automated and can do the stuff for me. When I heard about the ArchUnit for the first time, I wanted to give it a try and attach it to the project but frankly speaking… I did not have many expectations from that. It was a surprise that after writing just a few ArchUnit tests I was able to find a bunch of broken conventions in the code I thought was already clean. I have added few simple tests in a few minutes, just like that:
- classes in particular packages have to follow naming conventions (like *Controller, *Repository, *Service, etc.)
- no public classes for Spring beans, no public methods in controllers, no public Spring constructors, no field injections, and so on
- no cyclic dependencies and clear dependencies between packages
ArchUnit will fail the build once it finds any rule broken. There are lots of benefits from this approach:
- just one another tool that does the job for me and for the peer who has to do the code review
- fails immediately in the test phase of the build - fast feedback about the issue. It also points the exact piece of the code that breaks the build
- very friendly API and lots of great examples available: ArchUnit-Examples
- helpful for people that join/contribute to the project to understand and follow the established design and conventions.
If you have not used the ArchUnit, just give it a try. For me, it is just one another must-have in terms of the code quality tools now.
You can see some use cases here: ArchUnit use cases
I also encourage you to spend 8 minutes with Pawel who gave an excellent introduction to ArchUnit. Enjoy!