rspec/rules/S2208/java/rule.adoc

77 lines
2.1 KiB
Plaintext
Raw Normal View History

== 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.
2020-06-30 12:48:07 +02:00
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:
2020-06-30 12:48:07 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2020-06-30 12:48:07 +02:00
----
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]
----
2020-06-30 12:48:07 +02:00
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
2020-06-30 12:48:07 +02:00
[source,java,diff-id=1,diff-type=compliant]
2020-06-30 12:48:07 +02:00
----
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[]