Analyzing Code Dependencies (part II)

Posted on by alexandra.rusina

When you have cleaned up unnecessary dependencies, you certainly don’t want them to appear again. But if you work in a team, this is very probable to happen. So, how to avoid illegal dependencies?
Of course, you can periodically analyze and clean up the code as it is described in Analyzing Code Dependencies (part I). But there is a simpler way.
For example, you need to separate UI and business layers of your application. Consider that you have the following simple project.
project_structure
In our example, the dependencies from the com.sample.businesslogic package to com.sample.ui are illegal. To specify this rule, you need to take several steps.
First, analyze dependencies for the package, and click Edit Rules in the Dependency Viewer tool window.
edit_dependency_rules
Then add a new rule to the dependency validator.
dependency_validator
Here ui and business are custom scopes. In this example, ui is defined by the following pattern:

src[testProject]:com.sample.ui.* || lib:javax.swing..*

The business scope simply includes the corresponding package:

src[testProject]:com.sample.businesslogic..*

When this rule is applied all illegal dependencies in the dependency viewer become red.
illegal_dependencies
From the viewer you can navigate to the location of the illegal dependencies. But of course it would be much better to be notified that the dependency is illegal right when you create it.
For this purpose, IntelliJ IDEA provides the “Illegal package dependencies” code inspection. When switched on, it highlights illegal dependencies in the editor.
illegal_dependencies_in_editor
Now you can easily avoid illegal dependencies by sharing project settings between the members of your team.

Note   This tip&trick was originally posted at www.javalobby.org.

Technorati tags: ,
Subscribe

Subscribe for updates