How can I create a Checkstyle rule to limit interactions between different root packages?
I have the following 3 root packages:
models
Unfortunately, what you want is very hard to do using the ImportControl check out of the box.
Here's why:
You already found out why your option 1 cannot work: There can only be one root package.
Option 2 is possible, but laborious. Let me go into some depth. I used the following two import control files, which disallow using models
from views
and views
from models
:
<!DOCTYPE import-control PUBLIC "-//Puppy Crawl//DTD Import Control 1.1//EN"
"http://www.puppycrawl.com/dtds/import_control_1_1.dtd">
<import-control pkg="views">
<allow pkg="views" />
<disallow pkg="models" />
</import-control>
<!DOCTYPE import-control PUBLIC "-//Puppy Crawl//DTD Import Control 1.1//EN"
"http://www.puppycrawl.com/dtds/import_control_1_1.dtd">
<import-control pkg="models">
<allow pkg="models" />
<disallow pkg="views" />
</import-control>
In my test setup, this basically worked, but there is a drawback: Every class gets a Checkstyle warning that the Import control file does not handle this package. This is because the ImportControl check expects all packages to reside under a common root (verified by looking at the Checkstyle 5.6 sources). So in the models
package, you get the warning from the check instance configured for the views
package, and vice versa.
There is also the added problem that the ImportControl check only works on the import statements, but does not find fully qualified references used directly in the code.
So, what can you do?