/**
* 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");
}
?>
虽然检查参数是一种确认 — 如果您要求参数处于某种状态,这将对使用方法的人很有帮助 — 但是您应该检查它们并抛出有意义的异常:
处理异常要尽量与出现的问题紧密相关。 专门处理每个异常。
切忌使用复制粘贴
您可以从其他地方将代码复制粘贴到自己的代码编辑器,但这样做有利也有弊。好的一面是,从一个示例或模板中复制代码能够避免很多错误。不好的一面是,这容易带来大量的类似编程方式。
一定要注意,不要将代码从应用程序的一部分复制粘贴到另一部分。如果您采用这种方式,请停止这个不良的习惯,然后考虑将这段代码重写为可重用的。一般而言,将代码放置到一个地方便于日后的维护,因为这样只需在一个地方更改代码。
不良习惯:类似的代码段
清单 9 给出了几个几乎一样的方法,只是其中的值不同而已。有一些工具可以帮助找到复制粘贴过来的代码(参见参考资料)。
清单 9. 不良习惯:类似的代码段







