Introducing Coding Constraints Using ArchUnit
Introduce certain design/coding level constraints to developers while implementing the functionalities with ArchUnit.
Join the DZone community and get the full member experience.Join For Free
How often have you experienced a well-defined and understood software architecture on paper, but then it falls apart when developers start implementing it?
Recently, while re-architecting legacy components in an application, I experienced the same. As more and more developers joined the team, it became a constant routine to make them aware of the design thought adopted in the architecture and how to adhere to it.
I know some of you may say, "Why not control the implementation during code-review?" Well technically you can, but in that case, the reviewer becomes the bottleneck in the whole SDLC process.
What if there was something that could enforce the design constraint in the form of the test cases, and should there be a violation of the agreed-upon design principle, to mark the build as failed?
My quest led me to a test library called ArchUnit.
ArchUnit is a test library that allows us to validate whether an application adheres to a given set of design consideration or architecture rules.
But, what all things constitute under design and architecture, well it can be anything of below:
- Field/Class/Method Naming convention
- Class dependency on other packages
- Class polymorphism design rules
- Checking existence of cyclic dependencies in the code
- Enforcing Layered or Onion architecture
Enough of theory, let's see how you can implement these.
ArchUnit has excellent integration with JUnit, so all you have to do is add the below dependency in your java maven pom file.
If you are using JUnit 5, add the below dependency:
If you are still stuck in the dark ages, this is for JUnit 4:
Let's write some tests.
If you are a seasoned developer, you might have guessed by now that ArchUnit works on the Java reflection. So it is imperative to control how many classes within the entire project should be analyzed for this rule.
This is achieved as below. Consider this a prerequisite for writing the tests.
- Let's enforce some naming convention
- Let's take an example of enforcing the coding standard on how to define logger
- Second example is of standards around defining Util class and its methods
- There are certain general coding rules/conventions defined in the ArchUnit itself. We can chain them together using CompositeArchRule.
- If the standard ArchUnit Java API methods are not sufficient for enforcing the conditions, users can create a custom ArchCondition and use it in the ArchRule.
- You can also enforce layered or onion architecture rules
- ArchUnit cannot analyze the annotations marked with Retention.SOURCE , typical examples are Lombok annotations.
I hope you have gained something new from this article.
Opinions expressed by DZone contributors are their own.