rspec/rules/S1905/java/rule.adoc
Angelo Buono ccbf7d7edc
Modify rule S1905: Migrate to LayC - Redundant casts should not be used (#3236)
Co-authored-by: Zsolt Kolbay <121798625+zsolt-kolbay-sonarsource@users.noreply.github.com>
2023-10-11 10:03:57 +00:00

83 lines
1.7 KiB
Plaintext

== Why is this an issue?
include::../description.adoc[]
=== Exceptions
Casting may be required to distinguish the method to call in the case of overloading:
[source,java]
----
class A {}
class B extends A{}
class C {
void fun(A a){}
void fun(B b){}
void foo() {
B b = new B();
fun(b);
fun((A) b); // Compliant, required to call the first method so cast is not redundant.
}
}
----
== How to fix it
To fix your code remove the unnecessary casting expression.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
class Example {
public void example(List<String> list) {
for (String item: (List<String>) list) { // Noncompliant, Remove this unnecessary cast to "List".
//...
}
}
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
class Example {
public void example() {
for (String foo : getFoos()) {
//...
}
}
public List<String> getFoos() {
return List.of("foo1", "foo2");
}
}
----
== Resources
=== Documentation
* Geeksforgeeks - https://www.geeksforgeeks.org/type-conversion-java-examples/[Type conversion in Java with Examples]
* Wikipedia - https://en.wikipedia.org/wiki/Type_conversion[Type Conversion]
* Wikipedia - https://en.wikipedia.org/wiki/Strong_and_weak_typing[Strong and Weak Typing]
* Wikipedia - https://en.wikipedia.org/wiki/Polymorphism_(computer_science)[ Polymorphism (Computer Science)]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]