I was wondering which code is more effective, meaning faster & reliable. When I have my client post data into my website, I don't allow them to use anything else other than Alphanumeric characters because there's no need for others. My question was, would an exception be faster and more reliable for this? Or should I stay away from exceptions in this purpose? Here's my code.
Normal Way -
function checkStr ($str)
{
if (preg_match('/[^0-9a-zA-Z]/', $str) > 0))
{
return false;
}
else
{
return true;
}
}
if (checkStr($_POST['field']) == true)
{
//continue
}
else
{
echo "Invalid characters";
}
Exception -
function checkStr ($str)
{
if (preg_match('/[^0-9a-zA-Z]/', $str) > 0)
{
throw new Exception('Invalid characters');
}
return true;
}
try
{
checkStr($_POST['field']);
//no exception, continue with code
}
catch (Exception $e)
{
echo $e->getMessage();
}
}
Exceptions have more overhead associated with them than normal program flow control features (if, else, elseif, etc), so purely from that point of view the first option is faster. Exceptions are tricky things, and because they're a relatively new addition to PHP people tend to overuse them. Normally, I try to only throw exceptions when the circumstances that have occured in the code are exceptional.
For example, if I have a function where the valid inputs are the integers 1-100, then I'd have it return true for an input of 40, false for an input of 493, and throw an exception for an input of "kumquat".
BTW, you can write the first version of your function in a single line:
function checkStr ($str)
{
return (preg_match('/[^0-9a-zA-Z]/', $str) > 0));
}
Although Exceptions will have some performance overhead, performance is not the only criterion. Consider also code size and complexity, and overall maintainability.
Very often I encounter code where return values from methods are not checked and hence errors are ignored.
Which code is easier to understand
if ( do this )
if (do that)
if (something else)
OK
else
bad something
else
bad that
else
bad this
or with exceptions
try
do this
do that
something else
catch
report error
I'm not a php programmer, but in Java I tend to use exceptions quite a lot.