The Psychology of Quality and More |
CHAPTER 8 : Language Usage
8.7 Using 'switch'The switch statement is more limited than the Pascal case, in that it can only switch on integers. Thus when it is required to switch on such as string values, it is better to use the if...else if... construct (see 8.3.4) than to artificially convert to an integer just to use the switch. Because the switch statement is effectively a glorified goto, execution starts from the selected case, and will happily fall into the next case and right out of the bottom of the switch statement, enabling such imaginative uses as:
switch ( ErrorNo )
This is very succinct, saving on vertical space. It is also very liable to error, especially if modified. It also does not cater for possible other cases. 8.7.1 Use of 'break'A simple standard is to insist that each case is independent of all other cases. This can be done if each case is terminated with a break. Thus the above example becomes:
switch ( ErrorNo )
Each case is now a separate 'chunk' which can be read and edited independently, although at the cost of duplicated code. If you wish to allow fall-through between coded case's, then this should be made very clear with a comment where the break should be:
case ERR2: ----------------------------------------------------- It is reasonable to allow fallthrough on multiple cases which execute the identical code:
...
8.7.2 Use of 'default'Defensive programming dictates that all possible case's should be catered for, even ones that are not expected. Thus the default statement should always be used. Putting it last makes it easier to find; it also helps readability:
switch ( ErrorNo )
Thus, if an error in a previous statement results in an invalid ErrorNo, then this will be caught in the default statement. Note that a break statement is used, even though it is clearly redundant here. This allows a simple "break on all case's" rule to be used. It will also preserve the code if a case is added later, after the default.
|
Site Menu |
Quality: | Quality Toolbook | Tools of the Trade | Improvement Encyclopedia | Quality Articles | Being Creative | Being Persuasive | |
And: | C Style (Book) | Stories | Articles | Bookstore | My Photos | About | Contact | |
Settings: | Computer layout | Mobile layout | Small font | Medium font | Large font | Translate | |
You can buy books here |
And the big |