当前位置: 电脑软硬件应用网 > 设计学院 > 网络编程 > PHP教程 > 正文 |
|
|||
PHP编程的五个良好习惯 | |||
2009-3-5 17:59:23 文/佚名 出处:互联网 | |||
良好习惯:易管理、功能专一的方法 清单 4 将原来的方法改写为更加紧凑、易读的方法。在这个示例中,将一个很长的方法分解为几个短方法,并且让每个短方法负责一件事情。这样的代码对将来的重用和测试都是大有裨益的。 清单 4. 良好习惯:易管理、功能专一的方法 <?php function createRssHeader() { return "<rss version="2.0">" . "<channel>" . "<title>My Great Feed</title>" . "<link>http://www.example.com/feed.xml</link>" . "<description>The best feed in the world</description>" . "<language>en-us</language>" . "<pubDate>Tue, 20 Oct 2008 10:00:00 GMT</pubDate>" . "<lastBuildDate>Tue, 20 Oct 2008 10:00:00 GMT</lastBuildDate>" . "<docs>http://www.example.com/rss</docs>" . "<generator>MyFeed Generator</generator>" . "<managingEditor>editor@example.com</managingEditor>" . "<webMaster>webmaster@example.com</webMaster>" . "<ttl>5</ttl>"; } function createRssFooter() { return "</channel></rss>"; } function createRssItem($title, $link, $desc, $date, $guid) { $item .= "<item>"; $item .= "<title>" . $title . "</title>"; $item .= "<link>" . $link . "</link>"; $item .= "<description> " . $description . "</description>"; $item .= "<pubDate>" . $date . "</pubDate>"; $item .= "<guid>" . $guid . "</guid>"; $item .= "</item>"; return $item; } function getUserMaxStories($db_link, $default) { $perfsQuery = sprintf("SELECT max_stories FROM user_perfs WHERE user= '%s'", mysql_real_escape_string($user)); $result = mysql_query($perfsQuery, $db_link); $max_stories = $default; if ($row = mysql_fetch_assoc($result)) { $max_stories = $row['max_stories']; } return $max_stories; } function writeRssFeed($user) { // Get the DB connection information $settings = parse_ini_file("rss_server.ini"); // look up the user's preferences... $link = mysql_connect($settings['db_host'], $settings['user'], $settings['password']) or die(mysql_error()); $max_stories = getUserMaxStories($link, 25); // go get my data $newsQuery = sprintf("SELECT * FROM stories WHERE post_date = '%s'", mysql_real_escape_string(time())); $result = mysql_query($newsQuery, $link); $feed = createRssHeader(); $i = 0; // build the feed... while ($row = mysql_fetch_assoc($result)) { if ($i < $max_stories) { $title = $row['title']; $link = $row['link']; $description = $row['description']; $date = $row['date']; $guid = $row['guid']; $feed .= createRssItem($title, $link, $description, $date, $guid); $i++; } else { break; } } mysql_close($link); $feed .= createRssFooter(); // write the feed out to the server... echo($feed); } ?> 将长方法拆分为短方法也是有限制的,过度拆分将适得其反。因此,不要滥用这个良好的习惯。将代码分成大量的片段就像没有拆分长代码一样,都会造成阅读困难。 为代码添加注释 要为代码添加良好的注释有时似乎和编写代码一样难。要了解应该为哪些内容添加注释并不容易,因为我们常常倾向于注释代码当前做的事情。注释代码的目的是不错的主意。在函数的不是很明显的头部代码块中,告诉读者方法的输入和输出,以及方法的最初目标。 注释代码当前做什么是很常见的,但这是不必要的。如果代码很复杂,不得不注释它当前在做什么,这将暗示您应该重写代码,让它更容易理解。学会使用良好的名称和更短的方法,在不提供注释说明其用途的情况下提高代码的可读性。 不良习惯:函数注释过多或不足 清单 5 中的注释仅告诉读者代码在做什么 — 它正在通过一个循环进行迭代或添加一个数字。但它忽略了它为什么 做当前的工作。这使维护该代码的人员不知道是否可以安全地更改代码(不引入新缺陷)。 清单 5. 不良习惯:函数注释过多或不足 <?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"); ?> 良好习惯:带注释的函数和类 清单 6 中的注释告诉读者类和方法的目的。该注释解释了为什么代码在做当前的工作,这对未来维护代码十分有用。可能需要根据条件变更而修改代码,如果能够轻松了解代码的目的,则修改起来很容易。 清单 6. 良好习惯:带注释的函数和类 <?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"); ?> 处理错误 根据大众的经验,如果要编写健壮的应用程序,错误处理要遵循 80/20 规则:80% 的代码用于处理异常和验证,20% 的代码用于完成实际工作。在编写程序的基本逻辑(happy-path)代码时经常这样做。这意味着编写适用于基本条件的代码,即所有的数据都是可用的,所有的条件符合预期。这样的代码在应用程序的生命周期中可能很脆弱。另一个极端是,甚至需要花大量时间为从未遇到过的条件编写代码。 这一习惯要求您编写足够的错误处理代码,而不是编写对付所有错误的代码,以致代码迟迟不能完成。 不良习惯:根本没有错误处理代码 清单 7 中的代码演示了两个不良习惯。第一,没有检查输入的参数,即使知道处于某些状态的参数会造成方法出现异常。第二,代码调用一个可能抛出异常的方法,但没有处理该异常。当发生问题时,代码的作者或维护该代码的人员只能猜测问题的根源。 清单 7. 不良习惯:不处理错误条件
良好习惯:处理异常 清单 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"); } ?> 虽然检查参数是一种确认 — 如果您要求参数处于某种状态,这将对使用方法的人很有帮助 — 但是您应该检查它们并抛出有意义的异常: ◆处理异常要尽量与出现的问题紧密相关。 ◆专门处理每个异常。 切忌使用复制粘贴 您可以从其他地方将代码复制粘贴到自己的代码编辑器,但这样做有利也有弊。好的一面是,从一个示例或模板中复制代码能够避免很多错误。不好的一面是,这容易带来大量的类似编程方式。 一定要注意,不要将代码从应用程序的一部分复制粘贴到另一部分。如果您采用这种方式,请停止这个不良的习惯,然后考虑将这段代码重写为可重用的。一般而言,将代码放置到一个地方便于日后的维护,因为这样只需在一个地方更改代码。 不良习惯:类似的代码段 清单 9 给出了几个几乎一样的方法,只是其中的值不同而已。有一些工具可以帮助找到复制粘贴过来的代码(参见 参考资料)。 清单 9. 不良习惯:类似的代码段 <?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"); ?> 良好习惯:带参数的可重用函数 清单 10 展示了修改后的代码,它将复制的代码放到一个方法中。另一个方法也进行了更改,它现在将任务委托给新的方法。构建通用的方法需要花时间设计,并且这样做使您能停下来思考,而不是本能地使用复制粘贴。但有必要进行更改时,对通用的方法投入的时间将得到回报。 清单 10. 良好习惯:带参数的可重用函数 <?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 代码的过程中养成本文讨论的良好习惯,您将能够构建易读、易理解、易维护的代码。使用这种方式构建的易维护代码将降低调试、修复和扩展代码所面临的风险。 |
|||
关于45IT | About 45IT | 联系方式 | 版权声明 | 网站导航 | |
Copyright © 2003-2011 45IT. All Rights Reserved 浙ICP备09049068号 |