经验分享:PHP编程的5个良好习惯(二)

开发 后端
本文介绍的是PHP编程的几个良好习惯,分为两篇为大家介绍,希望对你有帮助,一起来看吧!

学习良好的编程习惯能够提高代码质量和效率。像其他语言一样,开发人员可以用 PHP 编写出各种质量级别的代码。根据具体的情况,一般的开发人员往往比优秀的开发人员的效率低 10%~20%。优秀的开发人员的效率更高,因为他们拥有丰富的经验和良好的编程习惯。不良的编程习惯将会影响到效率。本文通过展示一些良好的编程习惯,帮助您成为更优秀的程序员。

上一篇>>

3. 为代码添加注释

要为代码添加良好的注释有时似乎和编写代码一样难。要了解应该为哪些内容添加注释并不容易,因为我们常常倾向于注释代码当前做的事情。注释代码的目的是不错的主意。在函数的不是很明显的头部代码块中,告诉读者方法的输入和输出,以及方法的最初目标。

注释代码当前做什么是很常见的,但这是不必要的。如果代码很复杂,不得不注释它当前在做什么,这将暗示您应该重写代码,让它更容易理解。学会使用良好的名称和更短的方法,在不提供注释说明其用途的情况下提高代码的可读性。

不良习惯:函数注释过多或不足

清单 5 中的注释仅告诉读者代码在做什么 — 它正在通过一个循环进行迭代或添加一个数字。但它忽略了它为什么 做当前的工作。这使维护该代码的人员不知道是否可以安全地更改代码(不引入新缺陷)。

清单 5. 不良习惯:函数注释过多或不足

  1. <?php  
  2. class ResultMessage  
  3. {  
  4. private $severity;  
  5. private $message;  
  6. public function __construct($sev$msg)  
  7. {  
  8. $this->severity = $sev;  
  9. $this->message = $msg;  
  10. }  
  11. public function getSeverity()  
  12. {  
  13. return $this->severity;  
  14. }  
  15. public function setSeverity($severity)  
  16. {  
  17. $this->severity = $severity;  
  18. }  
  19. public function getMessage()  
  20. {  
  21. return $this->message;  
  22. }  
  23. public function setMessage($msg)  
  24. {  
  25. $this->message = $msg;  
  26. }  
  27. }  
  28. function cntMsgs($messages)  
  29. {  
  30. $n = 0;  
  31. /* iterate through the messages... */ 
  32. foreach($messages as $m) {  
  33. if ($m->getSeverity() == 'Error') {  
  34. $n++; // add one to the result;  
  35. }  
  36. }  
  37. return $n;}  
  38. $messages = array(new ResultMessage("Error""This is an error!"),  
  39. new ResultMessage("Warning""This is a warning!"),  
  40. new ResultMessage("Error""This is another error!"));  
  41. $errs = cntMsgs($messages);  
  42. echo("There are " . $errs . " errors in the result.\n");  
  43. ?> 

复制代码良好习惯:带注释的函数和类

清单 6 中的注释告诉读者类和方法的目的。该注释解释了为什么代码在做当前的工作,这对未来维护代码十分有用。可能需要根据条件变更而修改代码,如果能够轻松了解代码的目的,则修改起来很容易。

清单 6. 良好习惯:带注释的函数和类

  1. <?php  
  2. /**  
  3. *The ResultMessage class holds a message that can be returned  
  4. * as a result of a process. The message has a severity and  
  5. * message.  
  6. *  
  7. * @author nagood  
  8. *  
  9. */ 
  10. class ResultMessage  
  11. {  
  12. private $severity;  
  13. private $message;  
  14. /**  
  15. * Constructor for the ResultMessage that allows you to assign  
  16. * severity and message.  
  17. * @param $sev See {@link getSeverity()}  
  18. * @param $msg  
  19. * @return unknown_type  
  20. */ 
  21. public function __construct($sev$msg)  
  22. {  
  23. $this->severity = $sev;  
  24. $this->message = $msg;  
  25. }  
  26. /**  
  27. * Returns the severity of the message. Should be one  
  28. * "Information", "Warning", or "Error".  
  29. * @return string Message severity  
  30. */ 
  31. public function getSeverity()  
  32. {  
  33. return $this->severity;  
  34. }  
  35. /**  
  36. * Sets the severity of the message  
  37. * @param $severity  
  38. * @return void  
  39. */ 
  40. public function setSeverity($severity)  
  41. {  
  42. $this->severity = $severity;  
  43. }  
  44. public function getMessage()  
  45. {  
  46. return $this->message;  
  47. }  
  48. public function setMessage($msg)  
  49. {  
  50. $this->message = $msg;  
  51. }  
  52. }  
  53. /*  
  54. * Counts the messages with the given severity in the array  
  55. * of messages.  
  56. * @param $messages An array of ResultMessage  
  57. * @return int Count of messages with a severity of "Error"  
  58. */ 
  59. function countErrors($messages)  
  60. {  
  61. $matchingCount = 0;  
  62. foreach($messages as $m) {  
  63. if ($m->getSeverity() == "Error") {  
  64. $matchingCount++;  
  65. }  
  66. }  
  67. return $matchingCount;  
  68. }  
  69. $messages = array(new ResultMessage("Error""This is an error!"),  
  70. new ResultMessage("Warning""This is a warning!"),  
  71. new ResultMessage("Error""This is another error!"));  
  72. $errs = countErrors($messages);  
  73. echo("There are " . $errs . " errors in the result.\n");  
  74. ?> 

#p#

4. 处理错误

根据大众的经验,如果要编写健壮的应用程序,错误处理要遵循 80/20 规则:80% 的代码用于处理异常和验证,20% 的代码用于完成实际工作。在编写程序的基本逻辑(happy-path)代码时经常这样做。这意味着编写适用于基本条件的代码,即所有的数据都是可用的,所有的条件符合预期。这样的代码在应用程序的生命周期中可能很脆弱。另一个极端是,甚至需要花大量时间为从未遇到过的条件编写代码。

这一习惯要求您编写足够的错误处理代码,而不是编写对付所有错误的代码,以致代码迟迟不能完成。

不良习惯:根本没有错误处理代码

清单 7 中的代码演示了两个不良习惯。***,没有检查输入的参数,即使知道处于某些状态的参数会造成方法出现异常。第二,代码调用一个可能抛出异常的方法,但没有处理该异常。当发生问题时,代码的作者或维护该代码的人员只能猜测问题的根源。

清单 7. 不良习惯:不处理错误条件

  1. <?php  
  2. // Get the actual name of the  
  3. function convertDayOfWeekToName($day)  
  4. {  
  5. $dayNames = array(  
  6. "Sunday",  
  7. "Monday",  
  8. "Tuesday",  
  9. "Wednesday",  
  10. "Thursday",  
  11. "Friday",  
  12. "Saturday");  
  13. return $dayNames[$day];  
  14. }  
  15. echo("The name of the 0 day is: " . convertDayOfWeekToName(0) . "\n");  
  16. echo("The name of the 10 day is: " . convertDayOfWeekToName(10) . "\n");  
  17. echo("The name of the 'orange' day is: " . convertDayOfWeekToName('orange') . "\n");  
  18. ?> 

复制代码良好习惯:处理异常

清单 8 展示了以有意义的方式抛出和处理异常。额外的错误处理不仅使代码更加健壮,它还提高代码的可读性,使代码更容易理解。处理异常的方式很好地说明了原作者在编写方法时的意图。

清单 8. 良好习惯:处理异常

  1. <?php  
  2. /**  
  3. * This is the exception thrown if the day of the week is invalid.  
  4. * @author nagood  
  5. *  
  6. */ 
  7. class InvalidDayOfWeekException extends Exception { }  
  8. class InvalidDayFormatException extends Exception { }  
  9. /**  
  10. * Gets the name of the day given the day in the week. Will  
  11. * return an error if the value supplied is out of range.  
  12. *  
  13. * @param $day  
  14. * @return unknown_type  
  15. */ 
  16. function convertDayOfWeekToName($day)  
  17. {  
  18. if (! is_numeric($day)) {  
  19. throw new InvalidDayFormatException('The value \'' . $day . '\' is an ' .  
  20. 'invalid format for a day of week.');  
  21. }  
  22. if (($day > 6) || ($day < 0)) {  
  23. throw new InvalidDayOfWeekException('The day number \'' . $day . '\' is an ' .  
  24. 'invalid day of the week. Expecting 0-6.');  
  25. }  
  26. $dayNames = array(  
  27. "Sunday",  
  28. "Monday",  
  29. "Tuesday",  
  30. "Wednesday",  
  31. "Thursday",  
  32. "Friday",  
  33. "Saturday");  
  34. return $dayNames[$day];  
  35. }  
  36. echo("The name of the 0 day is: " . convertDayOfWeekToName(0) . "\n");  
  37. try {  
  38. echo("The name of the 10 day is: " . convertDayOfWeekToName(10) . "\n");  
  39. } catch (InvalidDayOfWeekException $e) {  
  40. echo ("Encountered error while trying to convert value: " . $e->getMessage() . "\n");  
  41. }  
  42. try {  
  43. echo("The name of the 'orange' day is: " . convertDayOfWeekToName('orange') . "\n");  
  44. } catch (InvalidDayFormatException $e) {  
  45. echo ("Encountered error while trying to convert value: " . $e->getMessage() . "\n");  
  46. }  
  47. ?> 

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

  • 处理异常要尽量与出现的问题紧密相关。
  • 专门处理每个异常。

希望对你有帮助,接下一篇,经验分享:PHP编程的5个良好习惯(三)

【编辑推荐】

  1. PHP新手 详细介绍PHP代码规范
  2. PHP中IIS7实现基本身份验证的方法
  3. 分享PHP网站建设的流程与步骤
  4. PHP新手 学习基本语法
  5. PHP新手 学习变量和常量
责任编辑:于铁 来源: 大家论坛
相关推荐

2011-07-07 15:48:22

PHP编程习惯

2011-07-07 15:26:28

PHP编程习惯

2009-01-03 14:34:49

ibmdwPHP

2009-01-03 10:40:41

PHP编程代码

2011-07-14 22:04:16

VC++

2010-04-08 11:17:06

Unix操作系统

2022-04-08 14:38:43

程序员习惯终端

2010-06-11 14:35:18

UML序列图

2011-04-13 10:16:41

编程习惯

2011-03-29 12:41:49

编程

2020-04-22 10:35:07

编程学习技术

2011-07-15 15:10:37

PHP

2011-03-24 09:25:54

程序员编程

2022-10-08 10:42:20

Linux虚拟机

2020-11-02 13:03:28

MySQLSQL索引

2024-02-26 08:13:51

MySQLSQL性能

2010-09-02 12:54:30

CSS

2021-08-17 09:55:50

pandas 8indexPython

2009-10-20 09:42:16

VB.NET编程

2015-11-06 14:54:10

程序员习惯
点赞
收藏

51CTO技术栈公众号