The more times that I find myself helping somebody with a website that was originally built/designed by somebody else the more I have been running into a certain webmaster pet-peeve of mine. When your writing code – whether it’s for yourself or for someone else – comments/notes are pretty crucial alas they’re often overlooked by many. Not only does it make your code easier to read through for somebody else – but it acts as a great reference point for yourself as-well should you find yourself having to go back and make some changes to your code a year down the line. Just so that we’re on the same page this is what I am referring to:
// Shorten Text to 200 Characters $pos=strpos($content, ' ', 200); substr($content,0,$pos );
First off if you are writing code for somebody else – they’ll greatly appreciate being able to look through the code and have a quick idea of what does what. Even if you are writing something as short as the above example – it won’t take you more than a few more seconds to put a quick descriptive comment about how your code functions or what it does. Furthermore if you have to refer back to this code a year down the line – you can always refer back to your own comments to know what’s going on. Let’s take an example look at the following code:
for ($x = 1; $x < 11; $x++){ $type = ((($x%4)==0)?1:0); $output = (($type==0)?"hello":"goodbye"); for($i=0, $j=1+$type; $i < $j ;$i++){ echo "$x $output
"; } }
As it sits right now getting a perfect grasp of exactly what this bit does isn’t immediately clear. We see that there is a for loop that counts to 10, and only upon truly reading through everything line by line do we get the idea of what this script does (counts to 10 and says Hello each time except every 4th time – during which it says goodbye twice) . However with some comments added we can paint a clear picture of what the various steps do:
for ($x = 1; $x < 11; $x++){ // inside a given loop of ten iterations . . . // determine if this is a plain case or the 4th time // if it is the fourth time, load a 1 in $type; otherwise, load a 0. $type = ((($x%4)==0)?1:0); // prepare to respond with hello or goodbye based on the value previously set in $type $output = (($type==0)?"hello":"goodbye"); // echo $output once or twice based on value previously set in $type for($i=0, $j=1+$type; $i < $j ;$i++){ echo "$x $output
"; } }
So please webmasters of all levels – write some comments within your code.