编写PHP代码的过程中养成的良好习惯(4)

http://www.itjxue.com  2015-07-17 08:19  来源:未知  点击次数: 

处理错误

根据大众的经验,如果要编写健壮的应用程序,错误处理要遵循 80/20 规则:80% 的代码用于处理异常和验证,20% 的代码用于完成实际工作。在编写程序的基本逻辑(happy-path)代码 时经常这样做。这意味着编写适用于基本条件的代码,即所有的数据都是可用的,所有的条件符合预期。这样的代码在应用程序的生命周期中可能很脆弱。另一个极端是,甚至需要花大量时间为从未遇到过的条件编写代码。

这一习惯要求您编写足够的错误处理代码,而不是编写对付所有错误的代码,以致代码迟迟不能完成。

不良习惯:根本没有错误处理代码

清单 7 中的代码演示了两个不良习惯。第一,没有检查输入的参数,即使知道处于某些状态的参数会造成方法出现异常。第二,代码调用一个可能抛出异常的方法,但没有处理该异常。当发生问题时,代码的作者或维护该代码的人员只能猜测问题的根源。

清单 7. 不良习惯:不处理错误条件

<?php
// Get the actual name of the
function convertDayOfWeekToName($day)
{
$dayNames = array(
“Sunday”,
“Monday”,
“Tuesday”,
“Wednesday”,
“Thursday”,
“Friday”,
“Saturday”);
return $dayNames[$day];
}
echo(”The name of the 0 day is: ” . convertDayOfWeekToName(0) . “n”);
echo(”The name of the 10 day is: ” . convertDayOfWeekToName(10) . “n”);
echo(”The name of the ‘orange’ day is: ” . convertDayOfWeekToName(’orange’) . “n”);
?>

良好习惯:处理异常

清单 8 展示了以有意义的方式抛出和处理异常。额外的错误处理不仅使代码更加健壮,它还提高代码的可读性,使代码更容易理解。处理异常的方式很好地说明了原作者在编写方法时的意图。

清单 8. 良好习惯:处理异常

<?php
/**
* This is the exception thrown if the day of the week is invalid.
* @author nagood
*
*/
class InvalidDayOfWeekException extends Exception { }
class InvalidDayFormatException extends Exception { }
/**
* Gets the name of the day given the day in the week. Will
* return an error if the value supplied is out of range.
*
* @param $day
* @return unknown_type
*/
function convertDayOfWeekToName($day)
{
if (! is_numeric($day)) {
throw new InvalidDayFormatException(’The value ” . $day . ” is an ‘ .
‘invalid format for a day of week.’);
}
if (($day > 6) || ($day < 0)) {
throw new InvalidDayOfWeekException(’The day number ” . $day . ” is an ‘ .
‘invalid day of the week. Expecting 0-6.’);
}
$dayNames = array(
“Sunday”,
“Monday”,
“Tuesday”,
“Wednesday”,
“Thursday”,
“Friday”,
“Saturday”);
return $dayNames[$day];
}
echo(”The name of the 0 day is: ” . convertDayOfWeekToName(0) . “n”);
try {
echo(”The name of the 10 day is: ” . convertDayOfWeekToName(10) . “n”);
} catch (InvalidDayOfWeekException $e) {
echo (”Encountered error while trying to convert value: ” . $e->getMessage() . “n”);
}
try {
echo(”The name of the ‘orange’ day is: ” . convertDayOfWeekToName(’orange’) . “n”);
} catch (InvalidDayFormatException $e) {
echo (”Encountered error while trying to convert value: ” . $e->getMessage() . “n”);
}
?>

虽然检查参数是一种确认 — 如果您要求参数处于某种状态,这将对使用方法的人很有帮助 — 但是您应该检查它们并抛出有意义的异常:

◆处理异常要尽量与出现的问题紧密相关。

◆专门处理每个异常。

(责任编辑:IT教学网)

更多