46 lines
1.2 KiB
Plaintext
46 lines
1.2 KiB
Plaintext
This rule raises an issue when an iteration over the items of a ``++Collection++`` is performed on a super-type of the type handled by the ``++Collection++``.
|
|
|
|
|
|
Relying on ``++Object++`` or any classes between ``++Object++`` and the real class handled by the ``++Collection++`` is not recommended. While it's accepted by the language, this practice reduces readability of the code and forces to down-cast the item of the ``++Collection++`` to be able to call a method on it while simply using the correct type in the iteration makes things more clear and simple.
|
|
|
|
|
|
== Noncompliant Code Example
|
|
|
|
[source,java]
|
|
----
|
|
public Collection<Person> getPersons() { ... }
|
|
|
|
for (Object item : getPersons()) { // Noncompliant
|
|
Person person = (Person) item; // Noncompliant; it's required to down-cast to the to correct type to use "item"
|
|
person.getAdress();
|
|
}
|
|
----
|
|
|
|
|
|
== Compliant Solution
|
|
|
|
[source,java]
|
|
----
|
|
for (Person person : getPersons()) { // Compliant
|
|
person.getAddress() ;
|
|
}
|
|
----
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::message.adoc[]
|
|
|
|
include::highlighting.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|