Monday, June 18, 2007

Comments

When you comment your code, what, exactly, are you documenting? It's a question that I think a lot of developers should ask themselves. What kind of information would be valuable for CluelessNewbie_01 as he peruses your code?

My approach, though I don't always adhere to this, has lately been to explain why the code is doing something, rather than what. I feel that if I feel the need to explain what, then I should probably start renaming symbols and refactor in order to make the code easier to understand.

Take for example the following PHP code:

protected function formatHumanReadableXML(DOMElement $delRoot = null){
if (!isset($delRoot)){
$delRoot = $this->ddcOwner->documentElement;
// Remove the whitespace
$this->removeWhitespace();
}
// Copy the children into an array
$arChildren = array();
foreach($delRoot->childNodes as $dndChild)
$arChildren[] = $dndChild;
.
.
.
.
}

Now, were those comments very helpful? No? You could tell what was going on by just reading the code, couldn't you? I've changed the code to be more helpful in the comments:


protected function formatHumanReadableXML(DOMElement $delRoot = null){
if (!isset($delRoot)){
$delRoot = $this->ddcOwner->documentElement;
/* Remove the whitespace, because this brings the document
to a common starting point, containing no whitespace, so
we can add tabs and breaks at our leisure*/
$this->removeWhitespace();
}
/* Copy the children into an array before looping over them, since
we may be appending children to this element (thereby changing
the childNodes list) */
$arChildren = array();
foreach($delRoot->childNodes as $dndChild)
$arChildren[] = $dndChild;
.
.
.
.
}


Now can you see what the point of that code is? A world of difference, I think.