Add iterable variable type validation in for loop

Noncompliant code example:

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

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

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.


1 Like