php best practices 1 - Handle unexpected conditions

Are you handling all the possible conditions under which your programs will run?

For instance, do you always have a "default" case in you "switch" statements?

switch($some_value)
{
case 1:
$another_value = 1;
break;
case 2:
$another_value = 4;
break;
}
return(1 / $another_value);

What if $some_value is not 1 nor 2?

Notice: Undefined variable: another_value

Warning: Division by zero

What about "if" conditions? Do you have an "else" code section to all important "if" statements?

If your program is not expecting certain conditions but those conditions are not impossible to occur, having simple calls to error_log may help you to be aware of the problems under unexpected situations.

switch($some_value)
{
case 1:
$another_value = 1;
break;
case 2:
$another_value = 4;
break;
default:
error_log('unexpected some_value '.$some_value.' found ');
exit;
}

0 comments:

Post a Comment

Share this post with your friends