Req #10032 [NEW]: intentional programming
| From: | tbarta at gmail dot com | Date: | Tue, 06 Feb 2007 04:33:47 +0000 |
| Subject: | Req #10032 [NEW]: intentional programming | ||
| Groups: | php.pear.doc | ||
| Request: | Send a blank email to pear-doc+get-9401@lists.php.net to get a copy of this message | ||
From: tbarta at gmail dot com
Operating system:
Package version:
PHP version: Irrelevant
Package: Documentation
Bug Type: Feature/Change Request
Bug description: intentional programming
Description:
------------
The "Comments" chapter of Coding standards says:
"Non-documentation comments are strongly encouraged. A general rule of
thumb is that if you look at a section of code and think "Wow, I don't
want to try and describe that", you need to comment it before you forget
how it works."
However, it makes no mention of alternative refactorings that could
improve the code readability (sometimes called Intentional Programming).
Some methods used:
* Break a complex statement into multiple simpler statements
* Introduce a named temporary variable or query
I apologize if this bug report is poorly formatted - I haven't submitted
any PHP bugs before!
Test script:
---------------
Some examples are:
Turn this:
{{{
if (is_array($this->callback)) {
$callback = (is_object($this->callback[0]) ?
strtolower(get_class($this->callback[0])) :
$this->callback[0]) . '::' .
$this->callback[1];
}
}}}
...into this:
{{{
if (is_array($this->callback)) {
$class_name = is_object($this->callback[0]) ?
strtolower(get_class($this->callback[0])) :
$this->callback[0]);
$callback = "$object::{$this->callback[1]}";
}
}}}
Both examples have the same number of lines. The second example reduces
parenthetical nesting by breaking the statement apart and explicitly names
a concept used in the code, reducing the cognitive complexity for a
reader.
Turn this:
{{{
// if we have an HTTP error that is a 304 error
if ($e == $GLOBALS['XML_RPC_err']['http_error'] &&
strstr($r->faultString(), '304 Not Modified') !== false) {
return $this->cache['content'];
}
}}}
...into this:
{{{
$http_has_error = ($e == $GLOBALS['XML_RPC_err']['http_error'];
$not_modified = strstr($r->faultString(), '304 Not Modified') !== false;
if ($http_has_error && $not_modified) {
return $this->cache['content'];
}
}}}
In this case, the refactored example is longer than the original.
However, a reader can understand either of the boolean tests or the
if-block independently of each other.
In many cases, one-liner comments such as this can be turned into
"executable comments" or "self-documenting code" which is then guaranteed
to avoid common comment-related problems (e.g. someone updates the source
but doesn't update the comment).
--
Edit bug report at http://pear.php.net/bugs/bug.php?id=10032&edit=1
--