Code duplication, Listing 24.4


#1

Two things bother me about Listing 24.4:

  1. The listeners are defined in two different ways: one named and the other unnamed. This bothers me since it seems somehow untidy and asymmetric. At least it’s not pleasing to my eyes. Why not define an “enterButtonListener” right after the “numberButtonListener”?

  2. The fact that there are two, almost identical, listeners bothers me as well. Is there a way to define one listener then determine in onClick which one it is? Then, use a switch statement to act on each one?


#2
  1. If you prefer that style, then go ahead. In our case, we elected to use a named listener only where two buttons required the same listener implementation.

  2. In code, “almost identical” and “identical” are two very different things. :slight_smile:

Having said that, something like the solution you describe is commonly used to allow a single method to handle code for multiple buttons. It’s not our favorite style, but many folks do like it. Here’s what it looks like:

public void onClick(View v) {
    if (v == enterButton) {
        // perform code for enter button
    } else {
        // perform code for number buttons
    }
}