ArchUnit
ArchUnit copied to clipboard
Extend Rule API to provide solutions for violations
When implementing #289 I wasn't sure how to write the rule text so that it's helpful and not too long, including
- that field injection is an anti-pattern
- links to blog posts why field injection is an anti-pattern
- provide possible solutions (constructor/setter injection)
The produced AssertionError for violations isn't really nice to read:
java.lang.AssertionError: Architecture Violation [Priority: MEDIUM] - Rule 'do not use field injection, because this is an anti-pattern, see https://example.org/this/is/a/very/long-link-to-the-first-blog-post for detailed explanations and https://example.org/this/is/another/link-to-a-different-blog-post for project guidelines; use constructor injection instead' was violated (2 times):
Field <org.Example.demoService> is annotated with @Autowired in (Example.java:0)
Field <org.Example.userService> is annotated with @Autowired in (Example.java:0)
Maybe we can extend the rule API so that rule authors can provide possible solutions for violations. I have something like Spring Boot's Failure Analyzer in mind. The error message could look like this:
java.lang.AssertionError: Architecture Violation [Priority: MEDIUM]
Rule:
do not use field injection, because this is an anti-pattern
Violations:
Field <org.Example.demoService> is annotated with @Autowired in (Example.java:0)
Field <org.Example.userService> is annotated with @Autowired in (Example.java:0)
Possible solution:
Use constructor injection instead. See https://example.org/this/is/a/very/long-link-to-the-first-blog-post for detailed explanations and https://example.org/this/is/another/link-to-a-different-blog-post for project guidelines.
Looks nice, but keep in mind that the list of violations might become quite long obscuring the possible solution :wink: Maybe Rule: ... Possible Solution: ... Current Violations: ... would be better to see it.
But we could also simply make it configurable. There is already com.tngtech.archunit.lang.ConfiguredMessageFormat, which takes care of the final text representation. An archunit.properties property like
messageFormat=com.my.CustomMessageFormat
Could maybe give the possibility to render the violations in any way you want (that was at least my original idea when I created ConfiguredMessageFormat, that it could be an easy hook...)