Alex Rivera | Logout

Should I worry about leaking the "this" pointer in Swing?

Asked 2012-02-07T22:00:58.307
19

I learned recently (in a class based on C#) that it's sometimes considered dangerous to register event listeners in an object's constructor, because those event listeners are given a reference to that object before the object is fully initialized, and could (at least in theory) attempt to access the object before construction is complete.

From what I understand, accessing an object before construction is complete can cause a crash, at least in some languages...if it doesn't cause a crash, then we would only care that the registration occur last, so our object is ready to receive events when we register its listeners.

I'm now starting on a new Swing GUI, and noticed that my standard practice when building Swing GUIs is to wire up the event listeners in the constructor.

It seems unlikely that the event listeners of Swing components would be called before the constructor is complete, as they presumably are not wired up until the component is added to a visible Swing container, which can only happen after construction.

So, is there a real reason to avoid that anti-pattern when working in Swing? And if so, what is the simplest way to go about it?

Edit
Report

1 Answer

0

Certainly constructors in industry standard Swing programming are often too big and the inheritance unnecessary. So long as you are sensible and don't kick anything off (cause events to be fired) before construction is complete, you should be okay. (And obviously, keep to the AWT EDT.)

answered 2012-02-07T23:58:38.803

Your Answer