|
|
Title | Answer: Switch |
Keywords | quick question answer, quiz answer, answer, Switch |
Categories | |
|
|
1. What does this code do?
The rarely used Switch statement takes a series of Boolean test values and corresponding result values. It returns the first return value if the first test value is True, it returns the second return value if the second test value is True, and so forth.
Note that the last test value is True so Switch returns the last return value if no other test passes.
This code takes a value between 0 and 10 and returns:
Value | Returns |
0 - 2 | 2 |
3 - 5 | 5 |
6 - 8 | 8 |
9 | 9 |
2. Can you reformat this code so it's easier to understand?
|
|
i_mod_10 = i Mod 10
j = Switch( _
i_mod_10 <= 2, 2, _
i_mod_10 <= 5, 5, _
i_mod_10 <= 8, 8, _
True, 9)
|
|
This code places each test and its corresponding return value on a seperate line so it's much easier to read.
3. Can you think of an alternative approach that's also easy to understand?
|
|
i_mod_10 = i Mod 10
Select Case i_mod_10
Case Is <= 2
j = 2
Case Is <= 5
j = 5
Case Is <= 8
j = 8
Case Else
j = 9
End Select
|
|
4. Which version is better?
Both of these versions are relatively easy to understand. The Select Case statement is much more common than Switch so most programmers will have less trouble understanding it at first glance.
If you run some tests, you'll find that Select Case is much faster than Switch. That shouldn't be a huge surprise because Switch needs to pass a variable-length array of parameters into a function while Select Case performs its calculations right then and there. In one test, Switch took about 0.0000083 seconds to perform the test while Select Case averaged roughly 0.0000005 seconds. Switch took more than 14 times as long.
The original tip I saw suggested Switch as a way to make the code smaller. It may do that if you don't put the tests on separate lines, but it also makes the code very hard to read and it makes the code slower. The second version is better in every reasonable way.
Moral
Write your code so it's clear, easy to understand, and works. Don't use fancy tricks and unusual statements (such as Switch) unless you are sure you have a need for them. Once the code works, you can modify it later if you need to do something tricky.
(Get it working correctly first is an important theme in my book Bug Proofing Visual Basic).
|
|
|
|
|