Have a sweet function written that requires valid variables? Make sure you’re validating those variables at the top of your function. Validating variables before (as apposed to while) they are used is key in making sure that important logic isn’t executed using crappy data.
Here’s an example of validating first, then executing:
/* The good... */
public function insertNewInvoiceItem($item, $quantity)
{
if(!$item instanceof Shop_Item) {
throw new InvalidArgumentException ('Expecting an item to be an instance of Shop_Item.');
}
if(!is_numeric($quantity)) {
throw new InvalidArgumentException('Quantity is not numeric.');
}
// We're good to go. Continue with the function...
}
The method above is also much cleaner than if... else... statements and limits the extra (perhaps useless) work required by your code:
/* The bad... */
public function insertNewInvoiceItem($item, $quantity)
{
if($item instanceof Shop_Item) {
// Do some $item stuff...
if(is_numeric($quantity)) {
// Do some $quantity calculations
} else {
// Uh oh, $quantity was bad but we've
// run some Shop_Item logic already.
}
}
else
{
// $item is not part of Shop_Item
}
}
I used a simple example to demonstrate my point but when this technique is used on more complex logic, it’s benefits are much more obvious.
Happy coding!
