1.2.1187. Switch Without Default¶
Always use a default statement in switch() and match().
Switch statements hold a number of ‘case’ that cover all known situations, and a ‘default’ one which is executed when all other options are exhausted.
For Match statements, a missing default will lead to the UnhandledMatchError`
exception being raised. On the other hand, the switch statement will simply exit without action nor alert.
Most of the time, switch() do need a default case, so as to catch the odd situation where the ‘value is not what it was expected’. This is a good place to catch unexpected values, to set a default behavior.
<?php
// Missing default
switch($format) {
case 'gif' :
processGif();
break 1;
case 'jpeg' :
processJpeg();
break 1;
case 'bmp' :
throw new UnsupportedFormat($format);
}
// In case $format is not known, then switch is ignored and no processing happens, leading to preparation errors
// switch with default
switch($format) {
case 'text' :
processText();
break 1;
case 'jpeg' :
processJpeg();
break 1;
case 'rtf' :
throw new UnsupportedFormat($format);
default :
throw new UnknownFileFormat($format);
}
// In case $format is not known, an exception is thrown for processing
?>
See also UnhandledMatchError.
1.2.1187.1. Connex PHP features¶
1.2.1187.1.1. Suggestions¶
Add a default case
Catch the UnhandledMatchError exception
1.2.1187.1.2. Specs¶
Short name |
Structures/SwitchWithoutDefault |
Rulesets |
|
Exakat since |
0.8.4 |
PHP Version |
All |
Severity |
Major |
Time To Fix |
Quick (30 mins) |
Precision |
Very high |
ClearPHP |
|
Examples |
|
Available in |