Chibueze Opata
Chibueze Opata

Reputation: 10034

Flipped switch statements?

Consider you have 10 boolean variables of which only one can be true at a time, and each time any one is 'switched on', all others must be 'turned off'. One of the problems that immediately arises is;

How can you quickly test which variable is true without necessarily having to linearly check all the variable states each time?

For this, I was thinking if it was possible to have something like:

switch(true)
{
   case boolean1:
       //do stuff
   ...
   //other variables
}

This looks like a bad way of testing for 10 different states of an object, but I think there're cases where this kind of feature may prove useful and would like to know if there's any programming language that supports this kind of feature?

Upvotes: 0

Views: 28

Answers (2)

Aadit M Shah
Aadit M Shah

Reputation: 74234

Traditionally, when you have such radio button boolean values you use an integer to represent them:

+------------+---------+--------------------+
|   BINARY   | DECIMAL | BINARY-LOGARITHMIC |
+------------+---------+--------------------+
| 0000000001 |       1 |                  0 |
| 0000000010 |       2 |                  1 |
| 0000000100 |       4 |                  2 |
| 0000001000 |       8 |                  3 |
| 0000010000 |      16 |                  4 |
| 0000100000 |      32 |                  5 |
| 0001000000 |      64 |                  6 |
| 0010000000 |     128 |                  7 |
| 0100000000 |     256 |                  8 |
| 1000000000 |     512 |                  9 |
+------------+---------+--------------------+

Let's call the variable holding this boolean value flag. We can quickly jump to some code based on the flag by indexing a random access array of functions:

var functions = [ function0
                , function1
                , function2
                , function3
                , function4
                , function5
                , function6
                , function7
                , function8
                , function9
                ];

functions[flag]();          // quick jump

However, you will have to pay for the function call overhead.

Upvotes: 1

Joe Breschler
Joe Breschler

Reputation: 71

There isn't a language feature that offers this behavior. But as an alternative, you could use the Command Pattern, in conjunction with a Priority Queue. This assumes that you would be able to prioritize what checks should be done.

Upvotes: 2

Related Questions