rspec/rules/S6322/java/rule.adoc

44 lines
1.6 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
The Java Collections framework defines interfaces such as `java.util.List` or `java.util.Map`. Several implementation classes are provided for each of those interfaces to fill different needs: some of the implementations guarantee a few given performance characteristics, some others ensure a given behavior, for example immutability.
Among the methods defined by the interfaces of the Collections framework, some are declared as "optional": an implementation class may choose to throw an `UnsupportedOperationException` when one of those methods is called. For example, `java.util.Collections.emptyList()` returns an implementation of `java.util.List` which is documented as "immutable": calling the `add` method on this object triggers an `UnsupportedOperationException`.
When calling one of the "optional" methods, a developer should therefore make sure that the implementation class on which the call is made indeed supports this method.
=== Noncompliant code example
2022-02-04 17:28:24 +01:00
[source,java]
----
List<String> list = Collections.emptyList();
if (someCondition) {
list.add("hello"); // Noncompliant; throws an UnsupportedOperationException
}
return list;
----
=== Compliant solution
2022-02-04 17:28:24 +01:00
[source,java]
----
List<String> list = new ArrayList<>();
if (someCondition) {
list.add("hello");
}
return list;
----
or
2022-02-04 17:28:24 +01:00
[source,java]
----
if (someCondition) {
return Collections.singletonList("hello");
}
return Collections.emptyList();
----
== Resources
* https://docs.oracle.com/javase/8/docs/technotes/guides/collections/overview.html[Collections Framework Overview] in the Java documentation