DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Finally, an ORM That Matches Modern Architectural Patterns!
  • Dependency Injection
  • Mastering Unit Testing and Test-Driven Development in Java
  • Comprehensive Guide to Unit Testing Spring AOP Aspects

Trending

  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  • FIPS 140-3: The Security Standard That Protects Our Federal Data
  • Beyond Simple Responses: Building Truly Conversational LLM Chatbots
  • Agentic AI for Automated Application Security and Vulnerability Management
  1. DZone
  2. Coding
  3. Java
  4. Introducing Coding Constraints Using ArchUnit

Introducing Coding Constraints Using ArchUnit

Introduce certain design/coding level constraints to developers while implementing the functionalities with ArchUnit.

By 
Pravin Tarte user avatar
Pravin Tarte
·
May. 20, 21 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
8.2K Views

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 

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:

Java
 




xxxxxxxxxx
1


 
1
<dependency>
2
    <groupId>com.tngtech.archunit</groupId>
3
    <artifactId>archunit-junit5</artifactId>
4
    <version>0.18.0</version>
5
    <scope>test</scope>
6
</dependency>



If you are still stuck in the dark ages, this is for JUnit 4:

Java
 




x



1
<dependency>
2
    <groupId>com.tngtech.archunit</groupId>
3
    <artifactId>archunit-junit4</artifactId>
4
    <version>0.14.1</version>
5
    <scope>test</scope>
6
</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.

Java
 




xxxxxxxxxx
1


 
1
@AnalyzeClasses(packages = "com.archunit",
2
        importOptions = {ImportOption.DoNotIncludeTests.class, ImportOption.DoNotIncludeJars.class})
3
// Analysing the classes defined in the com.archunit package and ignoring jar and test classes
4
public class CodingRulesTests {
5
  
6
}



  • 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
Java
 




xxxxxxxxxx
1


 
1
@ArchTest
2
static final ArchRule loggers_should_be_private_static_final =
3
fields().that().haveRawType(Logger.class)
4
          .should().beStatic()
5
          .andShould().bePrivate().
6
           andShould().beFinal().
7
           because("It's our team's agreed convention");


Java
 




xxxxxxxxxx
1


 
1
@ArchTest
2
static final ArchRule utility_methods_should_be_public_static = 
3
            methods().that().areDeclaredInClassesThat().
4
            resideInAnyPackage("..util..").
5
            should().bePublic().
6
            andShould().beStatic();


         

  • There are certain general coding rules/conventions defined in the ArchUnit itself. We can chain them together using CompositeArchRule.
Java
 




xxxxxxxxxx
1
12


 
1
// Classes should not access System.in , System.out or System.err
2
// Classes should not use java util logging
3
// Classes should not use joda time
4
// Methods should not throw generic exception
5
// For spring classes, there should be any field injection (@Autowired), use constrctor injection
6
@ArchTest
7
static final ArchRule implement_general_coding_practices =          CompositeArchRule.of(GeneralCodingRules.NO_CLASSES_SHOULD_ACCESS_STANDARD_STREAMS)
8
            .and(GeneralCodingRules.NO_CLASSES_SHOULD_THROW_GENERIC_EXCEPTIONS)
9
            .and(GeneralCodingRules.NO_CLASSES_SHOULD_USE_JAVA_UTIL_LOGGING)
10
            .and(GeneralCodingRules.NO_CLASSES_SHOULD_USE_JODATIME)
11
            .and(GeneralCodingRules.NO_CLASSES_SHOULD_USE_FIELD_INJECTION)
12
            .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.
Java
 




x
18


 
1
// Below Arch Condition enforcing the standard for defining the rest endpoint. Asking to put root as archUnit
2
static final ArchCondition<JavaClass> have_top_level_request_mapping_annotation_should_have_archUnit_as_base =
3
new ArchCondition<JavaClass>("Fld annotated with @RequestMapping shld contain archUnit") {
4
    @Override
5
   public void check(JavaClass javaClass, ConditionEvents conditionEvents) {
6
   String[] values = javaClass.getAnnotationOfType(RequestMapping.class).value();
7
     boolean result = Arrays.stream(values).anyMatch(v -> v.contains("archUnit"));
8
     if (!result) {
9
         conditionEvents.add(SimpleConditionEvent.violated(javaClass,
10
                 javaClass.getSimpleName() + " Rest Controller don't have archUnit in Request mapping "));
11
                    }
12
                }
13
            };
14

          
15

          
16
static ArchRule enforce_rest_controller_standards =
17
            classes().that().resideInAnyPackage("..controller..").and()
18
            .areAnnotatedWith(RestController.class).                   should(have_top_level_request_mapping_annotation_should_have_archUnit_as_base);



  • You can also enforce layered or onion architecture rules
Java
 




x


 
1
LayeredArchitecture arch = layeredArchitecture()
2
   // Define layers within the project
3
  .layer("Controller").definedBy("..controller..")
4
  .layer("Service").definedBy("..service..")
5
  .layer("Persistence").definedBy("..persistence..")
6
  // Add dependency constraints
7
  .whereLayer("Controller").mayNotBeAccessedByAnyLayer()
8
  .whereLayer("Service").mayOnlyBeAccessedByLayers("Presentation")
9
  .whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service");
10

          



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. 

Coding (social sciences) unit test Java (programming language) Software architecture

Opinions expressed by DZone contributors are their own.

Related

  • Finally, an ORM That Matches Modern Architectural Patterns!
  • Dependency Injection
  • Mastering Unit Testing and Test-Driven Development in Java
  • Comprehensive Guide to Unit Testing Spring AOP Aspects

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!