快速业务通道

PHP编程的五个良好习惯

作者 佚名技术 来源 NET编程 浏览 发布时间 2012-05-22
y;
  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. 不良习惯:不处理错误条件

<?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("

凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站: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号