rspec/rules/S6212/java/rule.adoc

51 lines
1.4 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
In Java 10 https://openjdk.java.net/jeps/286[Local-Variable Type Inference] was introduced. It allows you to omit the expected type of a variable by declaring it with the ``++var++`` keyword.
2021-05-12 01:17:24 +00:00
While it is not always possible or cleaner to use this new way of declaring a variable, when the type on the left is the same as the one on the right in an assignment, using the ``++var++`` will result in a more concise code.
2021-04-28 16:49:39 +02:00
2022-04-19 13:23:42 +02:00
This rule reports an issue when the expected type of the variable is the same as the returned type of assigned expression and the type can be easily inferred by the reader, either when the type is already mentioned in the name or the initializer, or when the expression is self-explanatory.
2021-04-28 16:49:39 +02:00
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
MyClass myClass = new MyClass();
2022-04-19 13:21:32 +02:00
int i = 10; // Type is self-explanatory
2021-05-09 01:17:04 +00:00
2022-04-19 13:21:32 +02:00
MyClass something = MyClass.getMyClass(); // Type is already mentioned in the initializer
2021-05-09 01:17:04 +00:00
2022-04-19 13:21:32 +02:00
MyClass myClass = get(); // Type is already mentioned in the name
2021-05-09 01:17:04 +00:00
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
var myClass = new MyClass();
2021-05-09 01:17:04 +00:00
var i = 10;
var something = MyClass.getMyClass();
var myClass = get();
2021-04-28 16:49:39 +02:00
----
2021-04-28 16:49:39 +02:00
== See
* https://openjdk.java.net/jeps/286[JEP 286: Local-Variable Type Inference]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
include::highlighting.adoc[]
endif::env-github,rspecator-view[]