5个php编程的好习惯
有些人问,优秀程序员和大牛有什么区别,大概有10到20种吧。因为大牛有很好的编程习惯和丰富的经验,所以他们非常的高效。如果不好的编程习惯出现在你的代码里,你的代码效率就会降低。本文阐述一些好的编程习惯,他们可以让你成为更好的程序员。
这些习惯能让你的代码在高效运行的同时提高可维护性。你写代码的时候,可能大部分时间都浪费在维护上了,程序的维护代价很高。培养良好的编程习惯,如模块化设计,可以让你的代码可读性更好,从而容易维护。
代码中的问题往往伴随着不良的编程习惯,而且后者会导致代码不好修改并可能出现新的缺陷。下面有五个好的编程习惯,将帮你避免这些陷阱:
使用友好的命名方式。 使用更精悍短小的代码。 注释你的代码。 编写异常处理。 永远,永远不要复制粘贴.(玉米:我深深的同意这一点) 下面的章节将解释这些习惯。
良好的命名方式是最重要的编程习惯,因为好的命名会让代码易懂,好懂。代码的可读性决定它的可维护性。即使你在代码没有写注释,如果它可读性好的话,它也修改起来也会简单。你应该在练习开时就使用良好的命名方式,让你的代码像一本书一样。
例1包含一个过短的变量名,写出这样的代码非常不好弄懂,而且函数名也没有清晰的描述出这个方法是做什么的。函数名表示了函数的功能,如果它却是做别的用途的,那就会误导别人。
例2则给出了使用良好命名方式的代码。重新命名函数是为了更好的反映它们的功能。变量也重新命名为描述性的。只有一个在循环中的$i还使用短的变量名。尽管有些人不同意,短变量名在循环中是请允许的——甚至更好些,因为它们清晰的起到了指针的功能。
我鼓励你在函数中分隔长的条件给函数命名,以便于描述这个条件。(玉米:这句话啥意思?5555)这个技巧会让你的代码容易阅读和扩展,因此它可以被抽象复用。如果条件发生了改变,这样也会很容易更新函数 .由于方法有一个见名知义的名字,化码就不会失去它本来的意思或者变得难以理解。
使用更少的代码
编写代码、解决问题是一种容易的事情。当你解决一个正在发生的问题,编呀编,写呀写,你的方法越来越长。只要你回头使用更少的代码来重构,就是过了很久也没什么问题。
重构是个好主意,但你应该养成第一次就写出更短小精悍代码的习惯。在一个窗口上(玉米:不用翻页)就能看全的短小函数更容易理解。 要是一个函数长出了窗口,就很难理解了,因为你不能快速的从头到脚的浏览整个代码。
当构思一个方法的时候,你还应该养成一个让它们只做一件事情的习惯。以下因素写代码时应常注意。第一,只做一件事情的函数更易于复用。第二,这样的函数测试更方便。第三,这样的函数好读易懂方便改——如果必要的话——让它们尽可能的简单吧。
坏习惯:过长的函数(很多时候)
例三是过长函数的表现。它不知道自己要做什么。它做太多的事情,所以没有集成化。它更难以理解,不好debug和测试。它遍历文件建立列表,它给对象赋值,它做一些计算,……它耕田,它浇水,甚至做更多事情。(^_^)
例三. 坏习惯:过长函数
function writerssfeed($user)
{
// get the db connection information
// look up the user's preferences...
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
or die(mysql_error());
// query
$perfsquery = sprintf(select max_stories from user_perfs where user= '%s',
mysql_real_escape_string($user));
$result = mysql_query($query, $link);
$max_stories = 25; // default it to 25;
if ($row = mysql_fetch_assoc($result)) {
$max_stories = $row['max_stories'];
}
// go get my data
$perfsquery = sprintf(select * from stories where post_date = '%s',
mysql_real_escape_string());
$result = mysql_query($query, $link);
$feed = .
.
my great feed .
http://www.example.com/feed.xml .
the best feed in the world .
en-us .
tue, 20 oct 2008 10:00:00 gmt .
tue, 20 oct 2008 10:00:00 gmt .
http://www.example.com/rss .
myfeed generator .
editor@example.com .
webmaster@example.com .
5;
// build the feed...
while ($row = mysql_fetch_assoc($result)) {
$title = $row['title'];
$link = $row['link'];
$description = $row['description'];
$date = $row['date'];
$guid = $row['guid'];
$feed .= ;
$feed .= . $title . ;
$feed .= . $link . ;
$feed .= . $description . ;
$feed .= . $date . ;
$feed .= . $guid . ;
$feed .= ;
}
$feed .=
要是你再加更多东西到这个函数里,它会很快变得难以维护。
好习惯:可管理,集成化的函数
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.好习惯:注释函数和类
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%的代码没什么实际的用途。原始的代码通常都是在乐观的环境下编写的。这意味着代码可以在数据正常、一切理解的基础环境中工作的很好。但是这种代码在其生命周期内是脆弱的。在极端的情形中,你得花更多的时间来未很可能永远不会发生的状况编写相应代码。
这个习惯就是要你处理全部的出错情况,而且如果要是不这么做,你的代码永远也完不成。
坏习惯:不处理任何异常
好习惯: 防守型编程
例8表明处理并抛出异常是一件很有意义的事情。不只是额外的异常处理可以让代码健壮,但是这有助于提高代码的可读性。这种异常处理为原作者查看何时编写提供了一个很好的说明。
例8.好习惯:防守型编程
6) ($day 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表现了除了一些值所在位置之外很相近的几个方法。有些工具可以检验你的代码中复制粘贴的部分(去看看resources)。
例9.相似的代码块
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.好习惯 :可利用的带参函数
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的时候养成了本文中提到的好习惯,你写的代码将会好读、好懂、好维护。编写可维护代码的方式将让你的代码可以高度排错,并告别低级错误。
使用良好命名并用短代码块来组强你的代码会让你的代码简单明了。注明你代码的目的会让它的主旨明确易于理解。异常处理让你的代码健壮。最后,摒弃复制粘贴的恶习让你的代码整洁。
-----------------------------------------------------
玉米寄语:最后的这个复制粘贴的建议让我一身冷汗,想想其实有很多代码都是重复的工作,有时只是为了“快”,而把相似的代码又“复制”了一遍,虽然我没有使用ctrl+c\v 但是也是写了很多类似的代码,看来,review的事儿可以在世界和平的事儿之前考虑了。