In an article from the SitePoint PHP blog author Jeff Smith walks us through some advice he has about defensive programming in PHP, that is good practices for writing code that more gracefully handles potential error points.
Defensive programming, simply put, is programming with the intent to anticipate likely failure points. The goal is to circumvent those likely problems before they occur. You see the problem, right? There’s something inherently difficult with the advice “expect the unexpected” and it’s made many times worse when one alters it to “expect the unexpected and try to prevent it”. Let’s look at some practical examples.
He touches on a few of the most common places where errors could be introduced with unexpected input or functionality:
- Conditional Statements
- User Input (and trusting it....hint: never)
- Assumptions [Made] About Your Code
- Tunnel Vision (or not using good development practices)
- Consistency in Syntax and Naming
Each point in the list includes a brief summary of what to look out for and things you can do to prevent the problem. It's by no means an exhaustive list, but it is a good place to start.