39 lines
865 B
Plaintext
39 lines
865 B
Plaintext
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);
|
|
}
|
|
}
|
|
----
|
|
|
|
|