My Twitter

Posts Tagged ‘comments’

5 Tips for Coding Cleaner PHP

Monday, April 6th, 2009

PHP is lovely, though if you ever work with other people having good code is important. Here are some tips to improve your code.

Comment & Document

It’s really important that people understand why you are doing certain things in certain ways. Adding a quick comment above sections of code should be adequate, but documenting classes and functions (Even if it’s in a Wiki) is fantastic.

Give Variables, Functions and Classes Meaningful names

Nothing is worse than trying to figure out what a function called “SIDFE()” does. Give everything a name that if someone else looked at it, they could figure out what it does. The above is a real example I have come across while adjusting a clients website, if the other programmer had called it something like Scan_Incomming_Data_For_Evil() it would have been a lot more straightforward.

White space

whitespaceAs you can see, a little space here and there makes life a lot easier.

No one likes to have to search for the start of a function. Make sure you indent your code and keep it easy to read quickly.

Never Delete – Comment out

This one is a little hard to grasp, but imagine you just fixed a bug (say 100 lines of code to fix it) and something else has broken. It makes sense to be able to go back and see the old code without modification of the new code. Also, doing this helps people see where an old bug was (assuming you comment that the section of code is evil) for future reference.

Use Braces

Braces are those neat } and { things. If you don’t use them on various functions it’s a pain to figure out where a loop starts and finishes. This is especially important when programming on a large scale because no one likes debugging fugly code. Here is an example of good and bad code:

<?php
/* Examples of annoying code */
if ( $coder === 'Silly' ) bang_head(); 

while ( $coder === 'Silly' )
    bang_head();

/* Examples of good code*/
if ( $coder !== 'Silly' ){ Drink_Beer(); }

while ( $coder !== 'Silly' ){
    Drink_Beer();
}
?>

(more…)