Event Handling - Best Practice?
Greetings All
I am a C++ programmer who is attempting to learn Java with the ultimate aim of sitting the Oracle certification. I have (hopefully) a very simply question.
What is the best method for implementing listeners? Should I be putting them into anonymous inner classes or into a fully fledged private inner class? I have googled this question but my efforts haven't yielded a definite answer.
Many Thanks
Nikki
Re: Event Handling - Best Practice?
In my opinion there really isn't a best method. I've seen listeners implemented in a large number of ways...many with a different reason behind the implementation. My .02 - always think about code re-usability and adaptability to change. Sometimes writing inner classes locks you into an implementation that is difficult to modify in the future, in other situations it encapsulates the implementation details which can be beneficial - both are case dependent.
Re: Event Handling - Best Practice?
It depends if listener has to be used by multiple object than making it a full fleged class make sense but if its only attached to one element than having them as inner class is ok.
Re: Event Handling - Best Practice?
Oracle suggests use of inner classes for listeners. Switch statements are not good OOP design .
On the downside, you will start having tons of .class files for each event handler. That could ,for example, affect loading time of applets. But until then, it is better to go with the suggestion.
Re: Event Handling - Best Practice?
Quote:
Oracle suggests use of inner classes for listeners.
Curious where this is suggested. Do you have a link? Because from the standpoint of making code loosely couple, adaptable, and reusable this advice needs to be scrutinized.
Re: Event Handling - Best Practice?
Quote:
Originally Posted by
copeg
Curious where this is suggested. Do you have a link? Because from the standpoint of making code loosely couple, adaptable, and reusable this advice needs to be scrutinized.
You are right. Oracle just points out use of inner classes is inefficient but is a good OO design. But does not recommend
any of the methods
Quote:
We can not recommend a specific approach because one solution would not suit all situations.
General Information about Writing Event Listeners (The Java™ Tutorials > Creating a GUI With JFC/Swing > Writing Event Listeners)
It must be some pro-OO design website that I got the suggestion from. Among the three methods they compared
(switches, annonymous classes, inner classes), they suggested inner classes as best OO practice.
Re: Event Handling - Best Practice?
Just a quick post to say thank you all :cool:
Regards
Nikki