ArchUnit: Forget Architecture, It’s a Flexible and Intelligent Linter

ArchUnit: Forget Architecture, It’s a Flexible and Intelligent Linter

Piotr Kubowicz - March 14, 2022

ArchUnit is a nice tool that has finally received the attention it deserves. Unfortunately, people tend to focus on the very narrow use of it. The problem begins with the official website that advertises it as a library to check the architecture of Java/JVM systems, and more than that, loves to focus on UML diagrams. Plus, the name itself creates predictable associations. As a result, nearly all articles presenting ArchUnit repeat the same topics: detection of cyclic dependencies and counting software layers.

Don’t get me wrong; these aren’t completely unimportant things. But in daily life, there are down-to-earth issues that deserve more attention. For example, calling library functions that behave in unpredictable and dangerous ways. Or people forgetting to add some annotations and introducing bugs that are hard to diagnose.

You can use ArchUnit to guard against those non-architectural issues. Things that are hard to achieve in existing style checkers/linters like CheckStyle or ktlint can be done in ArchUnit without much effort. Contrary to those tools, rules written in ArchUnit are not language-specific. You can have a Java team writing some and sharing them with their colleagues using Kotlin in their team.

Recently I saw Spring Framework adopting ArchUnit, citing some reasons above. My team has been using the tool for more than a year. I suggest you learn about ArchUnit even if you have no interest in anything related to architecture.

An earlier version of this article is available in Polish: czytaj po polsku

How to Start

ArchUnit is not a heavy library. It’s enough to add a single dependency:

testImplementation("com.tngtech.archunit:archunit-junit5:0.22.0")

It does not carry too much with it:

./gradlew dependencies --configuration testComClass
...
\--- com.tngtech.archunit:archunit-junit5:0.22.0
     \--- com.tngtech.archunit:archunit-junit5-api:0.22.0
          \--- com.tngtech.archunit:archunit:0.22.0
               \--- org.slf4j:slf4j-api:1.7.30 -> 1.7.32

Tests using ArchUnit are short and readable:

@AnalyzeClasses(packages = ["com.acme"])
class ArchitectureTest {
    @ArchTest
    val absurdRule = noClasses().should().beAnonymousClasses()
}

They are executed together with standard JUnit tests. There is no need to configure anything additionally. We have a normal test; just the DSL is different.

Most of ArchUnit’s execution time is taken for startup, when your application bytecode is analyzed. In contrast, rule execution is fast. In our real-life code created by a single team, an ArchUnit test start takes 2 to 6 seconds, while a single rule execution is in tens of milliseconds. Which means that you should not fear adding more rules, as they won’t noticeably slow down the execution.

In case something in the examples is not clear to you, see the official documentation that does a great job in explaining the ArchUnit DSL.

Detecting JUnit Misuse

Let’s apply ArchUnit to a real problem. JUnit is somewhat tricky because it makes heavy use of annotations. You can make mistakes, and the compiler won’t stop you. Let’s see an example:

@Test
fun wrongAnnotation() =
    Role.values().map { dynamicTest("test $it") { assertCorrectFor(it) } }

@TestFactory
fun forgottenReturn() {
    Role.values().map { dynamicTest("test $it") { assertCorrectFor(it) } }
}

To an inexperienced eye, these are two test methods. But in reality, these are two pieces of dead code that will never catch any regression. In the first method, assertions won’t be executed because, without @TestFactory annotation, the framework won’t run returned dynamic tests. In the second method, the annotation is correct, but a return statement is missing.

IntelliJ is kind enough to show a warning for the first of the two methods above. That’s nice, but people can fail to see or just ignore IDE warnings. It’s better to have something automatic that fails the build and prevents merging such code.

For example, ArchUnit rules:

@ArchTest
val testMustBeVoid = noMethods().should(
    not(haveRawReturnType("void"))
        .and(beAnnotatedWith(Test::class.java))
)

@ArchTest
val testFactoryMustReturnType = noMethods().should(
    haveRawReturnType("void")
        .and(beAnnotatedWith(TestFactory::class.java))
)

We get a clear error message:

Architecture Violation [Priority: MEDIUM] - Rule 'no methods should not have raw return type void and be annotated with @Test' was violated (1 times): Method <pl.pkubowicz.dynamictest.ControllerTest.wrongAnnotation()> does not have raw return type void in (ControllerTest.kt:11) and Method <pl.pkubowicz.dynamictest.ControllerTest.wrongAnnotation()> is annotated with @Test in (ControllerTest.kt:11)

Before you copy the snippet above into your codebase, I must warn you that the rule regarding TestFactory is not precise. According to the documentation, a method annotated this way needs to return something like List<DynamicTest> or Stream<DynamicTest>. Why doesn’t my example cover this? An explanation will appear soon. Spoiler alert: we won’t be able to write a rule that requires that what is inside a list or a stream is for sure an instance of DynamicTest.

Dangerous Library Methods

Sometimes a library has some dark corners. Several methods that do bad things when you call them. The library as a whole may be ok: with a clear interface, well tested and maintained. Just those little details. You may end up using the library because its pros outweigh the cons.

A team can agree not to use bad parts of the library and watch out during code reviews. Maybe dark corners are marked by library authors as @Deprecated. Still, you are exposed to risk. People can fail to notice a bad call during a code review. IDE warnings can be ignored. There will be new people in the team, and what if nobody tells them what things should not be used?

I think it’s better to have conventions like that in written form. An even better: in executable form.

ArchUnit is a great help in such cases. It’s easy to write that we don’t allow calling a particular method. Or even: that we don’t allow calling one overloaded version of a method, the one where the last parameter is String instead of Instant.

It’s possible because ArchUnit operates on bytecode. Typical style checkers/linters see code as text, so they don’t allow for such a fine-grained control.

The reason above was cited when recently Spring Framework added ArchUnit to their build:

It would be good to try to prohibit the use of the APIs that prevent configuration avoidance. Checkstyle won’t help as the necessary type of information isn’t available. Archunit is an option, though, as it has full type information available.

Enforcing Uniqueness

Sometimes things need to be unique, but it’s not easy to be sure of it. When using Spring Framework, we are safe: there will be an exception when loading a context where we declare two beans of the same name. In general, however, libraries may not have such a good developer experience.

For example, we use a migration tool where migrations can be assigned a number controlling the order in which they are executed. This is great, but there is nothing prohibiting using the same number twice. The application will run without any errors or warnings. It’s very hard to notice that migration execution is nondeterministic in such a case. It’s also not easy to write an integration test that will fail when an ordinal number is reused.

This is why we have an ArchUnit rule in our code that forbids such a reuse.

@ArchTest
fun migrationsMustHaveDistinctOrder(classes: JavaClasses) {
    val migrationsDuplicatingOrder = classes
        .filter { it.isAnnotatedWith(Migration::class.java) }
        .groupBy { it.getAnnotationOfType(Migration::class.java).order }
        .filter { (_, classes) -> classes.size > 1 }
    org.assertj.core.api.Assertions.assertThat(migrationsDuplicatingOrder)
        .isEmpty()
}

Earlier in the article, the rules were declarative; this one is more imperative. This is because previously, the high-level API of ArchUnit called Lang API was used. It’s convenient to use, but it cannot cover all use cases, like asserting the uniqueness of a value of an annotation. The last example uses “Core API”, where all the framework does is providing a list of classes, and it’s our job to do the rest. As a plus: we have full control over processing and assertions.

Limitations

ArchUnit operates on JVM bytecode, so on something that has suffered from type erasure. The consequence is that we are not able to write rules like: “no method declared in a controller should return SecretKey or Mono<SecretKey> or Flux<SecretKey>”. ArchUnit will see our code returning Mono<Object> and Flux<Object> everywhere, no matter what the sources contain. We won’t be able to control what is inside a Mono or a Flux (or a List, Stream, etc.). At least ArchUnit is clear about its limitations: the API allows writing rules with haveRawReturnType(), but there is no method haveReturnType().

Summary

ArchUnit is not just about controlling system architecture. It can enforce conventions in our code and help avoid traps some libraries have.

Sometimes a library does not validate that what we do makes sense (for example, JUnit allows writing a void @TestFactory). In such a case, we write the validation in our code as an ArchUnit rule.

Sometimes a part of a library code is confusing and dangerous, but for the sake of backward compatibility, authors don’t remove it. We can fix it: an ArchUnit rule can fail a build if a forbidden class or method is used.

It is possible to employ ArchUnit to enforce complex rules, where the compiler or conventional tests cannot help. Do you have classes that need to be assigned unique numbers? No problem, it’s easy to write a rule for it. Or maybe you have custom annotations that need to be assigned to some kind of classes – again, a simple rule.

ArchUnit rules execute fast. They can follow code evolution: you can write rules importing classes like regular code does. If a class is renamed or deleted, the compiler will tell you your rule does not work. IDE refactorings will work on your rules. This is not the case with style checkers/linters that treat code as text.

Consider adding ArchUnit to your code as a kind of high-level linter.

About the author

Piotr Kubowicz

Piotr Kubowicz

Software Engineer

Linkedin profile Twitter Github profile

Piotr is a polyglot developer who has been coding in Java for over ten years. He also tried many other languages, from C and Perl to Ruby.
During his time at nexocode, Piotr's primary focus has been on evolving team culture and ongoing projects by developing build automation and systems architecture to ensure delivery is smooth even as project codebases get bigger and more complex. As an active developer in the community, you can notice him speaking at various meetups and conferences.

Tempted to work
on something
as creative?

That’s all we do.

join nexocode

This article is a part of

Zero Legacy
36 articles

Zero Legacy

What goes on behind the scenes in our engineering team? How do we solve large-scale technical challenges? How do we ensure our applications run smoothly? How do we perform testing and strive for clean code?

Follow our article series to get insight into our developers' current work and learn from their experience. Expect to see technical details, architecture discussions, reviews on libraries and tools we use, best practices on software quality, and maybe even some fail stories.

check it out

Zero Legacy

Insights from nexocode team just one click away

Sign up for our newsletter and don't miss out on the updates from our team on engineering and teal culture.

Done!

Thanks for joining the newsletter

Check your inbox for the confirmation email & enjoy the read!

This site uses cookies for analytical purposes.

Accept Privacy Policy

In the interests of your safety and to implement the principle of lawful, reliable and transparent processing of your personal data when using our services, we developed this document called the Privacy Policy. This document regulates the processing and protection of Users’ personal data in connection with their use of the Website and has been prepared by Nexocode.

To ensure the protection of Users' personal data, Nexocode applies appropriate organizational and technical solutions to prevent privacy breaches. Nexocode implements measures to ensure security at the level which ensures compliance with applicable Polish and European laws such as:

  1. Regulation (EU) 2016/679 of the European Parliament and of the Council of 27 April 2016 on the protection of natural persons with regard to the processing of personal data and on the free movement of such data, and repealing Directive 95/46/EC (General Data Protection Regulation) (published in the Official Journal of the European Union L 119, p 1); Act of 10 May 2018 on personal data protection (published in the Journal of Laws of 2018, item 1000);
  2. Act of 18 July 2002 on providing services by electronic means;
  3. Telecommunications Law of 16 July 2004.

The Website is secured by the SSL protocol, which provides secure data transmission on the Internet.

1. Definitions

  1. User – a person that uses the Website, i.e. a natural person with full legal capacity, a legal person, or an organizational unit which is not a legal person to which specific provisions grant legal capacity.
  2. Nexocode – NEXOCODE sp. z o.o. with its registered office in Kraków, ul. Wadowicka 7, 30-347 Kraków, entered into the Register of Entrepreneurs of the National Court Register kept by the District Court for Kraków-Śródmieście in Kraków, 11th Commercial Department of the National Court Register, under the KRS number: 0000686992, NIP: 6762533324.
  3. Website – website run by Nexocode, at the URL: nexocode.com whose content is available to authorized persons.
  4. Cookies – small files saved by the server on the User's computer, which the server can read when when the website is accessed from the computer.
  5. SSL protocol – a special standard for transmitting data on the Internet which unlike ordinary methods of data transmission encrypts data transmission.
  6. System log – the information that the User's computer transmits to the server which may contain various data (e.g. the user’s IP number), allowing to determine the approximate location where the connection came from.
  7. IP address – individual number which is usually assigned to every computer connected to the Internet. The IP number can be permanently associated with the computer (static) or assigned to a given connection (dynamic).
  8. GDPR – Regulation 2016/679 of the European Parliament and of the Council of 27 April 2016 on the protection of individuals regarding the processing of personal data and onthe free transmission of such data, repealing Directive 95/46 / EC (General Data Protection Regulation).
  9. Personal data – information about an identified or identifiable natural person ("data subject"). An identifiable natural person is a person who can be directly or indirectly identified, in particular on the basis of identifiers such as name, identification number, location data, online identifiers or one or more specific factors determining the physical, physiological, genetic, mental, economic, cultural or social identity of a natural person.
  10. Processing – any operations performed on personal data, such as collecting, recording, storing, developing, modifying, sharing, and deleting, especially when performed in IT systems.

2. Cookies

The Website is secured by the SSL protocol, which provides secure data transmission on the Internet. The Website, in accordance with art. 173 of the Telecommunications Act of 16 July 2004 of the Republic of Poland, uses Cookies, i.e. data, in particular text files, stored on the User's end device.
Cookies are used to:

  1. improve user experience and facilitate navigation on the site;
  2. help to identify returning Users who access the website using the device on which Cookies were saved;
  3. creating statistics which help to understand how the Users use websites, which allows to improve their structure and content;
  4. adjusting the content of the Website pages to specific User’s preferences and optimizing the websites website experience to the each User's individual needs.

Cookies usually contain the name of the website from which they originate, their storage time on the end device and a unique number. On our Website, we use the following types of Cookies:

  • "Session" – cookie files stored on the User's end device until the Uses logs out, leaves the website or turns off the web browser;
  • "Persistent" – cookie files stored on the User's end device for the time specified in the Cookie file parameters or until they are deleted by the User;
  • "Performance" – cookies used specifically for gathering data on how visitors use a website to measure the performance of a website;
  • "Strictly necessary" – essential for browsing the website and using its features, such as accessing secure areas of the site;
  • "Functional" – cookies enabling remembering the settings selected by the User and personalizing the User interface;
  • "First-party" – cookies stored by the Website;
  • "Third-party" – cookies derived from a website other than the Website;
  • "Facebook cookies" – You should read Facebook cookies policy: www.facebook.com
  • "Other Google cookies" – Refer to Google cookie policy: google.com

3. How System Logs work on the Website

User's activity on the Website, including the User’s Personal Data, is recorded in System Logs. The information collected in the Logs is processed primarily for purposes related to the provision of services, i.e. for the purposes of:

  • analytics – to improve the quality of services provided by us as part of the Website and adapt its functionalities to the needs of the Users. The legal basis for processing in this case is the legitimate interest of Nexocode consisting in analyzing Users' activities and their preferences;
  • fraud detection, identification and countering threats to stability and correct operation of the Website.

4. Cookie mechanism on the Website

Our site uses basic cookies that facilitate the use of its resources. Cookies contain useful information and are stored on the User's computer – our server can read them when connecting to this computer again. Most web browsers allow cookies to be stored on the User's end device by default. Each User can change their Cookie settings in the web browser settings menu: Google ChromeOpen the menu (click the three-dot icon in the upper right corner), Settings > Advanced. In the "Privacy and security" section, click the Content Settings button. In the "Cookies and site date" section you can change the following Cookie settings:

  • Deleting cookies,
  • Blocking cookies by default,
  • Default permission for cookies,
  • Saving Cookies and website data by default and clearing them when the browser is closed,
  • Specifying exceptions for Cookies for specific websites or domains

Internet Explorer 6.0 and 7.0
From the browser menu (upper right corner): Tools > Internet Options > Privacy, click the Sites button. Use the slider to set the desired level, confirm the change with the OK button.

Mozilla Firefox
browser menu: Tools > Options > Privacy and security. Activate the “Custom” field. From there, you can check a relevant field to decide whether or not to accept cookies.

Opera
Open the browser’s settings menu: Go to the Advanced section > Site Settings > Cookies and site data. From there, adjust the setting: Allow sites to save and read cookie data

Safari
In the Safari drop-down menu, select Preferences and click the Security icon.From there, select the desired security level in the "Accept cookies" area.

Disabling Cookies in your browser does not deprive you of access to the resources of the Website. Web browsers, by default, allow storing Cookies on the User's end device. Website Users can freely adjust cookie settings. The web browser allows you to delete cookies. It is also possible to automatically block cookies. Detailed information on this subject is provided in the help or documentation of the specific web browser used by the User. The User can decide not to receive Cookies by changing browser settings. However, disabling Cookies necessary for authentication, security or remembering User preferences may impact user experience, or even make the Website unusable.

5. Additional information

External links may be placed on the Website enabling Users to directly reach other website. Also, while using the Website, cookies may also be placed on the User’s device from other entities, in particular from third parties such as Google, in order to enable the use the functionalities of the Website integrated with these third parties. Each of such providers sets out the rules for the use of cookies in their privacy policy, so for security reasons we recommend that you read the privacy policy document before using these pages. We reserve the right to change this privacy policy at any time by publishing an updated version on our Website. After making the change, the privacy policy will be published on the page with a new date. For more information on the conditions of providing services, in particular the rules of using the Website, contracting, as well as the conditions of accessing content and using the Website, please refer to the the Website’s Terms and Conditions.

Nexocode Team

Close

Want to be a part of our engineering team?

Join our teal organization and work on challenging projects.

CHECK OPEN POSITIONS