rspec/rules/S2293/java/rule.adoc

67 lines
2.7 KiB
Plaintext

== Why is this an issue?
Java uses angular brackets (`<` and `>`) to provide a specific type (the "type argument") to a generic type.
For instance, `List` is a generic type, so a list containing strings can be declared with `List<String>`.
Prior to Java 7, the type argument had to be provided explicitly for every occurrence where generics were used.
This often caused redundancy, as the type argument would have to be provided both when a field is declared and initialized.
Java 7 introduced the diamond operator (`<>`) to reduce the code's verbosity in some situations.
The type argument between the angular brackets should be omitted if the compiler can infer it.
Since the diamond operator was only introduced in Java 7, this rule is automatically disabled when the project's `sonar.java.source` is lower than `7`.
== How to fix it
The type argument should be omitted in the initialization if it is already present in the declaration of a field or variable.
For instance, a field with type `List<String>` can be initialized with `ArrayList<>()`, as the compiler will infer that `ArrayList<String>()` is the actually desired call.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
List<String> strings = new ArrayList<String>(); // Noncompliant, the compiler can infer the type argument of the constructor invocation
Map<String,List<Integer>> map = new HashMap<String,List<Integer>>(); // Noncompliant, the compiler can also infer complex type arguments
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
List<String> strings = new ArrayList<>(); // Compliant, the compiler will infer the type argument
Map<String,List<Integer>> map = new HashMap<>(); // Compliant, the compiler will infer the type argument
----
== References
* https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html[The Java(TM) Tutorials] - Type Inference (Generics)
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Replace the type specification in this constructor call with the diamond operator ("<>"). [(sonar.java.source not set. Assuming 7 or greater.)]
'''
== Comments And Links
(visible only on this page)
=== on 17 Dec 2014, 13:55:04 Nicolas Peru wrote:
Fine by me. This rule should probably be implemented only when we have figured a way to activate rules depending on version of java used.
=== on 17 Dec 2014, 14:46:31 Ann Campbell wrote:
\[~nicolas.peru] I've set it to off by default & tagged it java7 just like some of the other Java 7/8-specific rules. I think this could be implemented now & we trust the user to turn it on only when indicated.
endif::env-github,rspecator-view[]