patternjavaMinor
Anonymous Classes for Listeners
Viewed 0 times
anonymouslistenersforclasses
Problem
While working with Android GUI my approach to adding Listeners for GUI elements is usually:
Currently, I am at learning stage. However, will this approach be maintainence 'friendly' as I get working with more complex apps? If not, then what are suitable alternatives?
Button helpBt = (Button) findViewById(R.id.help_button);
helpBt.setOnClickListener(new View.OnClickListener() {
/* Code */
});Currently, I am at learning stage. However, will this approach be maintainence 'friendly' as I get working with more complex apps? If not, then what are suitable alternatives?
Solution
It depends on how much / Code / there is. If it's just a few lines, that's one thing. If it gets too large though, the reader will lose sight of the fact that you're creating an anonymous listener. I would say that if the anonymous listener is more than 5, or maybe 10 lines then you should use an inner class instead.
There comes a point where even an inner class is really too large though.
In general, questions about "When is too big?" are highly subjective, but failing to ask them, and failing to act on the answers leads to hard to read, difficult to maintain code.
Also, as biovamp pointed out, if you want to reuse the code, then you need to create a regular class.
There comes a point where even an inner class is really too large though.
In general, questions about "When is too big?" are highly subjective, but failing to ask them, and failing to act on the answers leads to hard to read, difficult to maintain code.
Also, as biovamp pointed out, if you want to reuse the code, then you need to create a regular class.
Context
StackExchange Code Review Q#10562, answer score: 7
Revisions (0)
No revisions yet.