From "Code Complete"
🎧 Listen to Summary
Free 10-min PreviewEffective Use and Ordering of 'case' Statements
Key Insight
The 'case' or 'switch' statement provides structured control flow, varying significantly by language, from C++ and Java's support for ordinal types with single values to Visual Basic's powerful range and combination notations. The ordering of cases within a 'case' statement is crucial for readability and efficiency, particularly in longer statements handling numerous events. Cases can be ordered alphabetically or numerically for equally important options, improving the ease of finding a specific case. Alternatively, prioritizing the normal case first, clearly indicating it with comments, or ordering by frequency—most frequently executed first—improves both efficiency and reader navigation, as common cases are found more quickly.
Keep the actions associated with each 'case' simple and concise; for complicated actions, extract them into separate routines and call these routines from within the 'case' block to maintain a clear statement structure. A critical pitfall to avoid is creating 'phony' variables solely to facilitate a 'case' statement (e.g., 'action = userCommand[0]'). Such practice is problematic because the simplified variable might not accurately represent the full context of the actual data, potentially leading to missed errors. For example, extracting only the first character of a user command for a 'case' statement could incorrectly trigger actions for multiple distinct commands that start with the same letter, bypassing proper error detection. Instead, use 'if-then-else-if' chains to evaluate the full, complex input.
The 'default' clause in a 'case' statement should be reserved for legitimate default scenarios or, ideally, for error detection. Using 'default' to catch the last remaining expected case is ill-advised as it removes valuable self-documentation and prevents the 'default' from serving its primary role of identifying unexpected or invalid inputs. Therefore, it is best practice to include a diagnostic message in the 'default' clause, such as 'DisplayInternalError("Internal Error 905: Call customer support.")', to flag unhandled conditions during development and in production. In C-like languages (C, C++, and Java), explicitly include a 'break' statement at the end of each 'case' block to prevent 'dropping through' and executing code for subsequent cases; intentional fall-through, while sometimes used, is generally discouraged due to its high propensity for errors during code modification and should be clearly documented with comments if absolutely necessary.
📚 Continue Your Learning Journey — No Payment Required
Access the complete Code Complete summary with audio narration, key takeaways, and actionable insights from Steve McConnell.