Checkstyle rule to limit interactions between root packages (with ImportControl?)

后端 未结 1 1530
借酒劲吻你
借酒劲吻你 2021-01-22 03:17

How can I create a Checkstyle rule to limit interactions between different root packages?

I have the following 3 root packages:

  • models
相关标签:
1条回答
  • 2021-01-22 03:39

    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?

    • Change your app so that you have a common root. This is best practice and generally a good idea.
    • Implement a custom check as a subclass of ImportControlCheck which adds an option for enabling/disabling the "Import control file does not handle this package" message, and otherwise go with your option 2.
    • If you are using Eclipse, there is also a third solution. You could use the advanced configuration dialog that the Checkstyle Eclipse plugin provides in order to restrict the ImportControl instances to their respective files. This would also eliminate the "Import control file does not handle this package" messages.
    0 讨论(0)
提交回复
热议问题