• Home
  • blog
  • More Tips for Defensive Programming in PHP

More Tips for Defensive Programming in PHP

The general definition of defensive programming (as seen in Part 1, an overview piece on Defensive Programming in PHP) being used here is thus:

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.

This definition is a wide one. Many people argue against defensive programming, but this is often because of the types of methods they have seen espoused by some as defensive programming. Defensive programming should not be viewed as a way to avoid test driven development or as a way to simply compensate for failures and move on.

“Fail Fast” should not be seen as a counter to defensive programming. It all falls under the same umbrella. What are these methods, if not ways to anticipate that your program may fail, and either prevent those, or else ways in which to handle those failures appropriately?

Shield target being hit by arrows

Fail Fast, and Loudly

Simply put, failing fast and loudly means that when an error occurs, it will do so as early as possible, and alert whomever it should alert, as opposed to silently continuing on in an error state that may cause more issues. Here is an excellent article on fail-fast style development. The premise of fail-fast methodology is to fail when acquiring input that might later compromise the program (or, more generally, to enter a failure state as soon as any problems could possibly be detected, rather than allowing bad data to travel and a program to run un-checked, or worse, bad data to be stored somewhere). This is most useful when dealing with user input, or dealing with input that is arriving from outside the script, module, or even out of your system via an API. An example of where this could be employed would be a check for invalid values or data types passed into functions.

Continue reading %More Tips for Defensive Programming in PHP%