Article
Effortless (or Better!) Bug Detection with PHP Assertions
Other Easy Techniques
Assertions aren't the only tool that can help with early bug warning. Here are some others.
- Error Levels
Consider setting error levels toE_ALLduring development. Sure, you'll receive some notices that may not matter, say about a variable being referenced before set when all you want to know is whether it'sNULL. But when you reference an unset variable that should have a value, you'll be happy PHP told you about it so quickly. It's worth developing the habit of keeping your code in a state that doesn't trigger any warnings or notices, so when they do occur you'll know you've got something to look into.If you choose, you can integrate notices, warnings, and errors with phpAssertUnit by adapting the code shown above and providing a suitable error handler for
set_error_handler. - HTML Validation
Most PHP code generates HTML for Websites. Another easy way to find issues early is to use an HTML validator to check what your code is generating. There are many validation services available, including a good free one at http://validator.w3.org/.
- Unit Testing
Modern development methodologies such as Extreme Programming advocate that you write unit tests before you write code. Whether or not you want to go this far, you'll find you spend less time writing unit tests if you have help automating their execution. Consider using PhpUnit, a terrific open source unit test harness based on JUnit for Java.Incidentally, the effects of assertions and unit tests are complementary. Leave assertions enabled for the unit tests and you'll automatically increase the number and coverage of tests on your code.
Whether your project involves one person, a small team working in the same office, a large team distributed around the globe, or something in between, assertions offer important benefits. Not only do they help you communicate your assumptions, they also tell you when your assumptions are wrong. They repay the small investment in time to create them with the big rewards of earlier and easier diagnosis and repair of problems in the code. Using them will save you time.