好习惯:可复用的带参函数
例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");
?>
|
|