Java Callback Frameworks – Why Are Wrapper Classes Not Suited?

event-programmingframeworksjava

I just read the question what are callback frameworks?, where the asker cites the following from Effective Java:

The disadvantages of wrapper classes are few. One caveat is that
wrapper classes are not suited for use in callback frameworks, wherein
objects pass selfreferences to other objects for subsequent
invocations (“callbacks”).

So I am curious, why are wrapper classes not suited for use in callback frameworks? And can you provide an example of what the problem is?

Best Answer

The next line of Effective Java is helpful in clarifying the issue:

"Because a wrapped object doesn't know of its wrapper, it passes a reference to itself(this) and callbacks elude the wrapper. This is known as the SELF problem [Lieberman86]."

It seems like a trivial thing to make sure that all references to an object are via its wrapper, but wrappers are generally injected when a need arises and their design (their entire purpose of being) is to provide a low friction way to add more functionality to an existing class. This leads to subtle bugs, like the wrapper missing the event. Or the wrapper and wrapped object both registering for the same events - leading to duplicate processing and potential concurrency issues as well. If you don't know (don't have the source code) where callbacks are registered, it may be impossible to work around this problem. Additionally, wrappers are based on "pure" composition principles and callback frameworks force a "dirty" wrapper design.