Skip to content Skip to sidebar Skip to footer

How To Avoid Long Switch-case Statements?

I am currently coding an Android app, which will be used to count Traffic at Intersections. At a 4-way Intersection, the app would have 24 buttons. There are 4 groups, one for: eas

Solution 1:

There are many designs to decompose the 24-cases from a single long "switch" to something else. Common "OO" approaches would be to centralize in some kind of factory, or make 24 "independent actors" with the authority to do what you want.

For example, if you created 24 buttons that merely echo'd its log statement when pressed, that would eliminate the switch. If you have additional processing (beyond logging), then you need to make the strategic decision to "centralize" that processing (like in a single large switch statement, as you have now), or "decentralize" that processing into "independent actors" (like 24 "smart buttons") that have the context and authority to do what you want when pressed.

The "decentralized" design can then mature: You might have a single "DoIt" object/button, with the state being the log message, and you merely instantiate 24 of those instances (but only have a single class). Even if the 24 instances were to do completely different things, you can further abstract them out in other designs, like instantiating 24 objects/buttons that reference 24 different MyOperation1, MyOperation2, MyOperation3... class instances.

IMHO, the key design decision would be: What do you want to centralize? If they all do pretty much the same thing, you want one class, with 24 instances. If they behave fundamentally differently (you have very different logic in each of the case statements in your switch), then you may benefit from one-or-a-few processing classes, which may share a common base class, and then instantiate 24 buttons to each reference its processing class instance.


Solution 2:

How about an array of strings where id is the index into the array. So you get teh string

Log.v("output", myoutputstrings[id]);

You just need to initialise it somehow, possibly read it from a file or database.


Solution 3:

You can set the Tag property of the button (android:tag XML attribute) to "car,westbound,left" and retrieve it with the getTag() method.


Post a Comment for "How To Avoid Long Switch-case Statements?"