Add iterable variable type validation in for loop

java

(Anton Osynskyi) #1

Noncompliant code example:

for (Object item : getPersons()) {
  Person person = (Person)item;//need's cast to correct type
  person.getAdress();
}

public Collection<Person> getPersons() {}


The better way to iterate directly over Person type, Compliant solution:

for (Person person : getPersons()) {
  person.getAddress() ;//call methods of correct type
}
  • type : Code Smell

(Alexandre Gigleux) #3

Hi Anton,

Thanks for the suggestion.

I created this specification RSPEC-4838 and the corresponding implementation ticket SONARJAVA-2894. To be noted that nowadays IDEs are all able to generate for loops from macro and this avoids this kind of problem.

Regards