rspec/rules/S2208/java/rule.adoc
Renaud T 63e5b7219b
Modify S2208: Migrate To LayC - wildcard imports (#3279)
## Review

A dedicated reviewer checked the rule description successfully for:

- [x] logical errors and incorrect information
- [x] information gaps and missing content
- [x] text style and tone
- [x] PR summary and labels follow [the
guidelines](https://github.com/SonarSource/rspec/#to-modify-an-existing-rule)
2023-10-18 11:00:07 +02:00

77 lines
2.1 KiB
Plaintext

== Why is this an issue?
Using wildcards in imports may look cleaner as it reduces the number of lines in the import section and simplifies the code. +
On the other hand, it makes the code harder to maintain:
* It reduces code readability as developers will have a hard time knowing where names come from.
* It could lead to conflicts between names defined locally and the ones imported.
* It could later raise conflicts on dependency upgrade or Java version migration, as a wildcard import that works today might be broken tomorrow.
That is why it is better to import only the specific classes or modules you need.
=== Exceptions
Static imports are ignored by this rule. For example:
[source,java]
----
import static java.lang.Math.*;
----
will not raise an issue;
== How to fix it
Depending on your IDE you can solve this issue almost **automatically**: +
Look for **Organize/Optimize imports** actions.
These actions can also often be applied automatically on save. +
__Note:__ To make this work properly, you must adjust IDE settings to use a very high `allowed class count usage` before using wildcards.
Resolving this issue **manually** will require a step-by-step approach:
. Remove one wildcard import and note down compilation failures.
. For each missing class, import it back with the package prefix.
. When the code compiles again, proceed with the next wildcard import.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
import java.sql.*; // Noncompliant
import java.util.*; // Noncompliant
private Date date; // Date class exists in java.sql and java.util. Which one is this?
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
import java.sql.Date;
import java.util.List;
import java.util.ArrayList;
private Date date;
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Explicitly import the specific classes needed.
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]