Women in Technology

Hear us Roar



Article:
  Seven Low-Cost Ways to Improve Legacy Code
Subject:   Replace Listeners with Weak Listeners
Date:   2004-05-06 01:16:20
From:   ipreuss
This one can also easily introduce bugs. Consider the following common idiom:



myClass.addFooListener(new FooListener() {
public void fooHappened() {
reactToFoo();
}
});


If MyClass remembers its listeners using weak references, the new listener immediately is easy game for the garbage collector - which certainly is not the intent of the code.

Full Threads Oldest First

Showing messages 1 through 2 of 2.

  • Replace Listeners with Weak Listeners
    2004-05-07 15:09:21  Robert Simmons, Jr. | O'Reilly Author [View]

    True. That would not be a good thing. However, I am not a fan of anonymous classes as you read later in the article. I counsider it to be much better to refactor those into inner classes at the very least.

    Second of all, creating objects that you have no direct reference to is an iffy thing at best. This type of code is very prone to memory leaks.
    • Replace Listeners with Weak Listeners
      2004-05-11 08:48:20  ipreuss [View]

      Refactoring them to inner classes might be a good idea (though I am not as sensitive to small anonymous inner classes). Nevertheless


      • it's unlikely that given some huge legacy code, it's often unrealistic to do this in one swoop, and
      • if you don't hold a reference to the instance, named inner classe will provide you with the same kind of problem.


      I also don't think that not holding direct references to objects you create isn't always iffy at all. To the contrary: if the object you listen to has a shorter lifetime than the object creating the listener, it's the most elegant solution to make sure that the listener is destroyed as soon as it isn't needed any longer.