A little story about doing ForEach quickfix first then Generify... later
Take a look at this example code. I have a bunch of legacy code which is pre-JDK1.5 so it doesn't use templates and for each loop construct. Now, it is really easy to apply the "for loop replaceable by for each" quickfix to update the loops, but usually it is more difficult to Generify... the types esp. the code uses some other API which also uses unparametized types.
So, what has happened over time, is usually the loops were converted first,and then sometime later we ran Generify... The problem I am finding out is the two operations are not commutative.
Here is an example:
Ok, now if I Generify.. first and then convert to 'for each' loops, the result looks good:
elementList = Arrays.asList("Moe", "Larry", "Curly");
for (String name : elementList) {
System.out.println(name);
}
}
}
]]>
But if I first convert to 'for each' loops and then Generify... later, I get left with an
extra line "Object name = (String) anElementList;"
elementList = Arrays.asList("Moe", "Larry", "Curly");
for (Object anElementList : elementList) {
Object name = (String) anElementList;
System.out.println(name);
}
}
}
]]>
I guess IDEA needs an inspection to recognize that the type of "anElementList" can be changed from Object to String? I'm not sure would help anyway, because if I manually make that change, IDEA still won't flag the "Object name" variable as being redundant.
elementList = Arrays.asList("Moe", "Larry", "Curly");
for (String anElementList : elementList) {
Object name = (String) anElementList;
System.out.println(name);
}
}
}
]]>
One thing that I noticed, is that if you use Inspector General 'Rationalize Control Flow' after changing the type from Object to String in the for each loop, then 'Rationalize Control Flow' will remove the redundant variable. But, I haven't figured out how IDEA to do that.
elementList = Arrays.asList("Moe", "Larry", "Curly");
for (String anElementList : elementList) {
System.out.println(anElementList);
}
}
}
]]>
But one difference that remains still is that I lost my original name for the variable "name".
Moral of the Story: Resist the temptation to revel in the glory of 'for each' loops until your code has been blessed by Generify.. or wait until IDEA 8.0 when Rationalize Control Flow / Clean Code will wash away all unnecessary code.
Please sign in to leave a comment.