41 lines
893 B
Plaintext
41 lines
893 B
Plaintext
== Why is this an issue?
|
|
|
|
Setting the creation of an anonymous class inside a loop means a new instance will be created each time through the loop. But since the anonymous class is likely independent of any values that change within the loop, it's more efficient to create it once, outside the loop and use the same instance for each iteration.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,text]
|
|
----
|
|
private void setUpListeners(List<GuiObject> list) {
|
|
for (GuiObject gObj : list) {
|
|
gObj.addListener(new Listener() { // Noncompliant
|
|
public void onChange(Event e) {
|
|
// ...
|
|
}
|
|
});
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,text]
|
|
----
|
|
private void setUpListeners(List<GuiObject> list) {
|
|
|
|
Listener listener = new Listener() {
|
|
public void onChange(Event e) {
|
|
// ...
|
|
}
|
|
}
|
|
|
|
for (GuiObject gObj : list) {
|
|
gObj.addListener(listener);
|
|
}
|
|
}
|
|
----
|
|
|
|
|