Why is this an issue?
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
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
for (Person person : getPersons()) { // Compliant
person.getAddress() ;
}