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 FreeHow 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
ArchUnit has excellent integration with the other testing frameworks like JUnit, TestNg. ArchUnit tests get executed as part of regular unit test cases in a CI/CD pipeline, so feedback is immediate.
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:
xxxxxxxxxx
<dependency>
<groupId>com.tngtech.archunit</groupId>
<artifactId>archunit-junit5</artifactId>
<version>0.18.0</version>
<scope>test</scope>
</dependency>
If you are still stuck in the dark ages, this is for JUnit 4:
x
<dependency>
<groupId>com.tngtech.archunit</groupId>
<artifactId>archunit-junit4</artifactId>
<version>0.14.1</version>
<scope>test</scope>
</dependency>
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.
xxxxxxxxxx
packages = "com.archunit", (
importOptions = {ImportOption.DoNotIncludeTests.class, ImportOption.DoNotIncludeJars.class})
// Analysing the classes defined in the com.archunit package and ignoring jar and test classes
public class CodingRulesTests {
}
- 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
xxxxxxxxxx
static final ArchRule loggers_should_be_private_static_final =
fields().that().haveRawType(Logger.class)
.should().beStatic()
.andShould().bePrivate().
andShould().beFinal().
because("It's our team's agreed convention");
xxxxxxxxxx
static final ArchRule utility_methods_should_be_public_static =
methods().that().areDeclaredInClassesThat().
resideInAnyPackage("..util..").
should().bePublic().
andShould().beStatic();
- There are certain general coding rules/conventions defined in the ArchUnit itself. We can chain them together using CompositeArchRule.
xxxxxxxxxx
// Classes should not access System.in , System.out or System.err
// Classes should not use java util logging
// Classes should not use joda time
// Methods should not throw generic exception
// For spring classes, there should be any field injection (@Autowired), use constrctor injection
static final ArchRule implement_general_coding_practices = CompositeArchRule.of(GeneralCodingRules.NO_CLASSES_SHOULD_ACCESS_STANDARD_STREAMS)
.and(GeneralCodingRules.NO_CLASSES_SHOULD_THROW_GENERIC_EXCEPTIONS)
.and(GeneralCodingRules.NO_CLASSES_SHOULD_USE_JAVA_UTIL_LOGGING)
.and(GeneralCodingRules.NO_CLASSES_SHOULD_USE_JODATIME)
.and(GeneralCodingRules.NO_CLASSES_SHOULD_USE_FIELD_INJECTION)
.because("These are Voilation of general coding rules");
- 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.
// Below Arch Condition enforcing the standard for defining the rest endpoint. Asking to put root as archUnit
static final ArchCondition<JavaClass> have_top_level_request_mapping_annotation_should_have_archUnit_as_base =
new ArchCondition<JavaClass>("Fld annotated with @RequestMapping shld contain archUnit") {
public void check(JavaClass javaClass, ConditionEvents conditionEvents) {
String[] values = javaClass.getAnnotationOfType(RequestMapping.class).value();
boolean result = Arrays.stream(values).anyMatch(v -> v.contains("archUnit"));
if (!result) {
conditionEvents.add(SimpleConditionEvent.violated(javaClass,
javaClass.getSimpleName() + " Rest Controller don't have archUnit in Request mapping "));
}
}
};
static ArchRule enforce_rest_controller_standards =
classes().that().resideInAnyPackage("..controller..").and()
.areAnnotatedWith(RestController.class). should(have_top_level_request_mapping_annotation_should_have_archUnit_as_base);
- You can also enforce layered or onion architecture rules
x
LayeredArchitecture arch = layeredArchitecture()
// Define layers within the project
.layer("Controller").definedBy("..controller..")
.layer("Service").definedBy("..service..")
.layer("Persistence").definedBy("..persistence..")
// Add dependency constraints
.whereLayer("Controller").mayNotBeAccessedByAnyLayer()
.whereLayer("Service").mayOnlyBeAccessedByLayers("Presentation")
.whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service");
Known Limitations
- ArchUnit cannot analyze the annotations marked with Retention.SOURCE , typical examples are Lombok annotations.
I hope you have gained something new from this article.
If you are curious to find out more about the ArchUnit? Do visit their user guide and examples.
Opinions expressed by DZone contributors are their own.
Comments