Ingenio Home  | Blog Policies  | Help
Welcome to Community Sign in | Join | Help

Comment Your Code

For many programmers, this one is obvious. Commenting code is important for a number of reasons:
  1. It will remind you what all the code does - if you don't look at it every day, coming back to uncommented code is often a hassle.
  2. It will be a nice gift to your successor - when you develop code for a client, chances are you won't be the only one working on it during it's lifetime.
  3. It makes calls with me quicker! If I can skim over code by looking at valid comments, I can diagnose problems in a fraction of the time.
Here's an example:

<?php
$n = "1234.5678";
$n += pow( 10 , -3 );
$n = round( $n * pow( 10 , 2 ) ) / pow( 10 , 2 );
$n += pow( 10 , -3 );
$n = substr( $n , 0 , strpos( $n , '.' ) + 3 );
echo $n;
?>

So...what does that code do? Any idea at all? Wouldn't that be nicer if it was commented?

<?php
$n = "1234.5678";
// Instead of using PHP's built-in rounding function, manually round $n to 2 decimal places.
$n += pow( 10 , -3 );
$n = round( $n * pow( 10 , 2 ) ) / pow( 10 , 2 );
$n += pow( 10 , -3 );
$n = substr( $n , 0 , strpos( $n , '.' ) + 3 );
echo $n;
?>

This example gives rise to two other topics which I will cover later: Using Functions and Using Good Variable Names. When it's all said and done, here's the finished code:

<?php
function roundToTwo( $Number ) {
    // Instead of using PHP's built-in rounding function only, round $Number to two decimal places.
    $Number += pow( 10 , -3 );
    $Number = round( $Number * pow( 10 , 2 ) ) / pow( 10 , 2 );
    $Number += pow( 10 , -3 );
    $Number = substr( $Number , 0 , strpos( $Number , '.' ) + 3 );
    return $n;
}
echo roundToTwo( 1234.5678 );
?>
Published Saturday, August 04, 2007 12:04 PM by The PHP Doctor

Comment Notification

Subscribe to this post's comments using RSS

Comments

No Comments

What do you think?

(required) 
(required) 
(required) 
Enter the numbers you see into the
field below.
(required)