JnRouvignac / AutoRefactor

Eclipse plugin to automatically refactor Java code bases
Other
173 stars 37 forks source link

New refactoring - Simplify loops which only retain last iteration result #140

Open JnRouvignac opened 9 years ago

JnRouvignac commented 9 years ago

Given

The following condition:

String result1 = null;
for (String s : sortedSet) {
    result1 = s.toString();
}

String result2 = null;
for (String s : list) {
    result2 = s.toString();
}

When

... automatic refactorings are applied ...

Then

code is refactored to:

String result1 = !sortedSet.isEmpty() ? sortedSet.last().toString() : null;
String result2 = !list.isEmpty() ? list.get(list.size() - 1).toString() : null;

A similar change can be applied to Maps.

igorrosenberg commented 9 years ago

(Edited) (Watch out. This refactoring must not be applied if the set or the list is empty. In this case, result stays as null.) Previous edited comment referred to old description, current phrasing is good:

String result1 = !sortedSet.isEmpty() ? sortedSet.last().toString() : null;
String result2 = !list.isEmpty() ? list.get(list.size() - 1).toString() : null;

On 16 July 2015 at 00:45, Jean-Noël Rouvignac notifications@github.com wrote:

Given

The following condition:

String result1 = null;for (String s : sortedSet) { result1 = s.toString(); } String result2 = null;for (String s : list) { result2 = s.toString(); }

When

... automatic refactorings are applied ... Then

code is refactored to:

String result1 = sortedSet.last().toString();String result2 = list.get(list.size() - 1).toString();

— Reply to this email directly or view it on GitHub https://github.com/JnRouvignac/AutoRefactor/issues/140.

JnRouvignac commented 9 years ago

Yes, I saw I made a mistake and corrected it quickly. Thanks for watching ;)