[Java] Forbid classes from importing from a 'child' package

A new rule suggestion:

Prevent classes from importing from a sub-package.

Importing from a child or sub-package often indicates coupling to a specific implementation rather than referencing the interface of it. An import from a child package is likely to be a violation of a master-child relation.

  • snippet of Noncompliant Code

package com.some.cool.stuff;

// ERROR - you must not import from deeper/child packages
import com.some.cool.stuff.impl;

  • snippet of Compilant Code

package com.some.cool.stuff;

// OK - importing from parent is totally fine
import com.some.cool;

// OK - importing from package on same hierachy level is fine
import com.some.cool.extras;

// OK - importing from package on deeper packages in another part of the hierachy level is fine
import com.some.hot.stuff.reditems;

// OK??? - possible exception to the rule is a sub-package for Exception classes
import com.some.cool.stuff.exceptions;

  • type: Code Smell

Hi Stephen,

Thank you for this suggestion.
We prefer to not implement rules which are based on indices of bad practice, i.e. something “likely”. Developers disable those rules as they raise a high number of False Positives.

This is the difference between an Audit tool and a Continuous Integration tool. SonarQube is designed to be a CI tool, which means that it is used to block releases and pull request merges. It cannot do this if it is not very confident that there is a problem.

Cheers,

Nicolas

1 Like

Sorry, I do not understand. You have hundreds of code smell rules for Java. These code smell rules are not bugs; they are considered bad design or coding practice for one reason or another. We consider it bad practice to import classes from sub-packages as described above. I do not see the essential difference here.

The false positives rate is not related the type of the rule (code smell/bug/…). We strive to have very little false positives even for code smell rules as they also impact the Quality Gate and can block a release/pull request. It is used for the “Maintainability rating”.

As you said

An import from a child package is likely to be a violation of a master-child relation.

“likely” is not enough. There can be many exceptions. Even the JDK has imports to child packages.

@stephenrpalmer,

One thing I forgot to mention is that you can implement this rule as a custom rule if you want. The documentation is available here: https://docs.sonarqube.org/latest/extend/adding-coding-rules/