快速业务通道

PHP编程的五个良好习惯

作者 佚名技术 来源 NET编程 浏览 发布时间 2012-05-22
;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");
}
?>

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

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

◆专门处理每个异常。

切忌使用复制粘贴

您可以从其他地方将代码复制粘贴到自己的代码编辑器,但这样做有利也有弊。好的一面是,从一个示例或模板中复制代码能够避免很多错误。不好的一面是,这容易带来大量的类似编程方式。

一定要注意,不要将代码从应用程序的一部分复制粘贴到另一部分。如果您采用这种方式,请停止这个不良的习惯,然后考虑将这段代码重写为可重用的。一般而言,将代码放置到一个地方便于日后的维护,因为这样只需在一个地方更改代码。

不良习惯:类似的代码段

清单 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($message

凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

分享到: 更多

Copyright ©1999-2011 厦门凌众科技有限公司 厦门优通互联科技开发有限公司 All rights reserved

地址(ADD):厦门软件园二期望海路63号701E(东南融通旁) 邮编(ZIP):361008

电话:0592-5908028 传真:0592-5908039 咨询信箱:web@lingzhong.cn 咨询OICQ:173723134

《中华人民共和国增值电信业务经营许可证》闽B2-20100024  ICP备案:闽ICP备05037997号