Debugging is an important part of coding. One way to make the debugging process easier is to write quality code to begin with. This article, the first of two parts, will point out some of the most common coding errors, and help you identify problems in your code. It is excerpted from chapter 12 of Zend PHP Certification, written by George Schlossnagle et al (Sams; ISBN: 0672327090).
Making mistakes is human, and so is fixing them. In your day-to-day programming adventures, it's inevitable to introduce bugs in your PHP code, especially when you're writing very complex applications with tens of thousands of lines of code spread across tens of files.
When you're prototyping an application, being able to avoid common programming mistakes is important to ensure that your code will be well-written from the very start. In this chapter, we'll provide you with some guidelines on writing efficient code, debugging faulty scripts, and identifying bottlenecks when performance becomes an issue for both you and your clients.
Terms You'll Need to Understand
Bug
Coding standard
Code readability
Comparison operators
Performance
Caching
Portability
Techniques You'll Need to Master
Writing readable code
Proper commenting
Comparing heterogeneous data
Debugging
Identifying and preventing performance bottlenecks
Preventing performance issues
Improving database performance
Using content and bytecode caching
Coding Standards
Writing your code in a structured manner is, perhaps, the smartest decision you can make. Although there aren't any predefined coding standards that everyone in the programming community recognizes as better than the rest, deciding from the very beginning on a set of conventions will go a long way toward helping you make fewer mistakes.
Documenting your code is particularly important. To make this job—probably at the top of the Ten Most Hated Tasks of programmers worldwide—a bit easier, you can even use one of the many automated tools available on the market, such as PHPDocumentor, which can extract documentation directly from your code if you structure your comments in a particular way.
Regardless of how you introduce them in your applications, good comments and documentation will make sharing your code with other members of your team easier, as well as make sure that you'll remember what it does when you get back from that three-week vacation. Remember, preventing bugs is much better than hunting for them.
Extra whitespace and empty lines, although unimportant as far as the functionality of your code is concerned, can be an extremely valuable tool for writing better code:
if ($foo == 'bar')
{
$i = 0;
/**
* foreach loop, get the content out of it
*/
foreach ( .... )
{
}
}
By separating your code into logical groups, your source will be cleaner and easier to read. Also, indenting each line according to the code block it belongs to helps you figure out immediately what the structure of your script is.