清单 6. 良好习惯:带注释的函数和类
处理错误
根据大众的经验,如果要编写健壮的应用程序,错误处理要遵循 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. 良好习惯:处理异常
虽然检查参数是一种确认 — 如果您要求参数处于某种状态,这将对使用方法的人很有帮助 — 但是您应该检查它们并抛出有意义的异常:
◆处理异常要尽量与出现的问题紧密相关。
◆专门处理每个异常。
切忌使用复制粘贴
您可以从其他地方将代码复制粘贴到自己的代码编辑器,但这样做有利也有弊。好的一面是,从一个示例或模板中复制代码能够避免很多错误。不好的一面是,这容易带来大量的类似编程方式。
一定要注意,不要将代码从应用程序的一部分复制粘贴到另一部分。如果您采用这种方式,请停止这个不良的习惯,然后考虑将这段代码重写为可重用的。一般而言,将代码放置到一个地方便于日后的维护,因为这样只需在一个地方更改代码。
不良习惯:类似的代码段
清单 9 给出了几个几乎一样的方法,只是其中的值不同而已。有一些工具可以帮助找到复制粘贴过来的代码(参见 参考资料)。
清单 9. 不良习惯:类似的代码段
良好习惯:带参数的可重用函数
清单 10 展示了修改后的代码,它将复制的代码放到一个方法中。另一个方法也进行了更改,它现在将任务委托给新的方法。构建通用的方法需要花时间设计,并且这样做使您能停下来思考,而不是本能地使用复制粘贴。但有必要进行更改时,对通用的方法投入的时间将得到回报。
清单 10. 良好习惯:带参数的可重用函数
结束语
如果您在编写 PHP 代码的过程中养成本文讨论的良好习惯,您将能够构建易读、易理解、易维护的代码。使用这种方式构建的易维护代码将降低调试、修复和扩展代码所面临的风险。 使用良好的名称和更短的方法能够提高代码的可读性。注释代码的目的有利于代码理解和扩展。适当地处理错误会使代码更加健壮。最后,停止使用复制粘贴,保持代码干净,提高可重用性。
<?php /* * Counts the messages with the given severity in the array * of messages. * * @param $messages An array of ResultMessage * @return int Count of messages matching $withSeverity */ function countMessages($messages, $withSeverity) { $matchingCount = 0; foreach($messages as $m) { if ($m->getSeverity() == $withSeverity) { $matchingCount++; } } return $matchingCount; } /** * Counts the number of messages found in the array of * ResultMessage with the getSeverity() value of "Error" * * @param $messages An array of ResultMessage * @return unknown_type */ function countErrors($messages) { return countMessages($messages, "Errors"); } /** * Counts the number of messages found in the array of * ResultMessage with the getSeverity() value of "Warning" * * @param $messages An array of ResultMessage * @return unknown_type */ function countWarnings($messages) { return countMessages($messages, "Warning"); } /** * Counts the number of messages found in the array of * ResultMessage with the getSeverity() value of "Warning" * * @param $messages An array of ResultMessage * @return unknown_type */ function countInformation($messages) { return countMessages($messages, "Information"); } $messages = array(new ResultMessage("Error", "This is an error!"), new ResultMessage("Warning", "This is a warning!"), new ResultMessage("Error", "This is another error!")); $errs = countErrors($messages); echo("There are " . $errs . " errors in the result.n"); ?>
<?php /** * Counts the number of messages found in the array of * ResultMessage with the getSeverity() value of "Error" * * @param $messages An array of ResultMessage * @return unknown_type */ function countErrors($messages) { $matchingCount = 0; foreach($messages as $m) { if ($m->getSeverity() == "Error") { $matchingCount++; } } return $matchingCount; } /** * Counts the number of messages found in the array of * ResultMessage with the getSeverity() value of "Warning" * * @param $messages An array of ResultMessage * @return unknown_type */ function countWarnings($messages) { $matchingCount = 0; foreach($messages as $m) { if ($m->getSeverity() == "Warning") { $matchingCount++; } } return $matchingCount; } /** * Counts the number of messages found in the array of * ResultMessage with the getSeverity() value of "Information" * * @param $messages An array of ResultMessage * @return unknown_type */ function countInformation($messages) { $matchingCount = 0; foreach($messages as $m) { if ($m->getSeverity() == "Information") { $matchingCount++; } } return $matchingCount; } $messages = array(new ResultMessage("Error", "This is an error!"), new ResultMessage("Warning", "This is a warning!"), new ResultMessage("Error", "This is another error!")); $errs = countErrors($messages); echo("There are " . $errs . " errors in the result.n"); ?>
<?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"); } ?>
良好习惯:处理异常
<?php /** * The ResultMessage class holds a message that can be returned * as a result of a process. The message has a severity and * message. * * @author nagood * */ class ResultMessage { private $severity; private $message; /** * Constructor for the ResultMessage that allows you to assign * severity and message. * @param $sev See {@link getSeverity()} * @param $msg * @return unknown_type */ public function __construct($sev, $msg) { $this->severity = $sev; $this->message = $msg; } /** * Returns the severity of the message. Should be one * "Information", "Warning", or "Error". * @return string Message severity */ public function getSeverity() { return $this->severity; } /** * Sets the severity of the message * @param $severity * @return void */ public function setSeverity($severity) { $this->severity = $severity; } public function getMessage() { return $this->message; } public function setMessage($msg) { $this->message = $msg; } } /* * Counts the messages with the given severity in the array * of messages. * * @param $messages An array of ResultMessage * @return int Count of messages with a severity of "Error" */ function countErrors($messages) { $matchingCount = 0; foreach($messages as $m) { if ($m->getSeverity() == "Error") { $matchingCount++; } } return $matchingCount; } $messages = array(new ResultMessage("Error", "This is an error!"), new ResultMessage("Warning", "This is a warning!"), new ResultMessage("Error", "This is another error!")); $errs = countErrors($messages); echo("There are " . $errs . " errors in the result.n"); ?>
<?php class ResultMessage { private $severity; private $message; public function __construct($sev, $msg) { $this->severity = $sev; $this->message = $msg; } public function getSeverity() { return $this->severity; } public function setSeverity($severity) { $this->severity = $severity; } public function getMessage() { return $this->message; } public function setMessage($msg) { $this->message = $msg; } } function cntMsgs($messages) { $n = 0; /* iterate through the messages... */ foreach($messages as $m) { if ($m->getSeverity() == 'Error') { $n++; // add one to the result; } } return $n; } $messages = array(new ResultMessage("Error", "This is an error!"), new ResultMessage("Warning", "This is a warning!"), new ResultMessage("Error", "This is another error!")); $errs = cntMsgs($messages); echo("There are " . $errs . " errors in the result.n"); ?>
将长方法拆分为短方法也是有限制的,过度拆分将适得其反。因此,不要滥用这个良好的习惯。将代码分成大量的片段就像没有拆分长代码一样,都会造成阅读困难。 如果多编写几个这样的方法,维护就成了真正的难题了。良好习惯:说明性强并且简洁的名称
(责任编辑:admin) |