In a new post to his site Matthias Noback takes a look at the concept of assertions and some libraries including some effective ways to use them in your code for validation of values.
When you're looking at a function (an actual function or a method), you can usually identify several blocks of code in there. There are pre-conditions, there's the function body, and there may be post-conditions. The pre-conditions are there to verify that the function can safely proceed to do its real job. Post-conditions may be there to verify that you're going to give something back to the caller that will make sense to them.
[...] Sometimes the programming language itself can help with these pre-conditions: for instance, the language may support strict typing, which prevents certain types of invalid input to be provided. Some languages offer more advanced ways of defining pre-conditions, like pattern matching.
Following a brief use case for assertions (at a high level) he gets more specific to PHP and mentions two assertions libraries that could be used to add these kinds of checks to your code (in addition to PHP's own assert function). He then answers the "why use assertions?" question and some basic rules around using them:
- don't use assertions to validate user input, use it to validate function arguments.
- don't use assertions to validate return values from other functions.
- don't use assertions as a replacement for exceptions.
For each of these, he provides a summary with a bit more background and code examples to help illustrate the point. He ends the post with some useful "rules of thumb" when using assertions and a reminder:
Assertions are sanity checks. When they would be left out, you should still have a correctly function application. They should never become user-facing errors.