Exceptions: Error Codes Vs Class Names
| From: | Davey | Date: | Sat, 28 Aug 2004 03:45:50 +0000 |
| Subject: | Exceptions: Error Codes Vs Class Names | ||
| Groups: | php.pear.dev | ||
| Request: | Send a blank email to pear-dev+get-32990@lists.php.net to get a copy of this message | ||
Hey PEARs, Greg,
I am not trying to start another debate, I just want to state some facts!
I have done some benchmarking with some fake code, one using a single class with a class constant for each type of error, and one using a seperate class for each type of error.
I chose the rather random number of 30 errors in each case (so in the first there was 30 constants and the second 30 classes).
I ran the random scenario that error 17 was thrown in each case, and
caught it.
My findings are this:
The definition of a single class with 30 constants is about 4 times faster than of the 30 seperate classes, however:
because with the single class we have to check the error code using:
catch (errors $exception) {
if ($exception->getCode() == exception_class::CONST) {
echo $exception;
}
}
as opposed to with the other method which means only the error we want
to check for is caught:
catch (error17 $exception) {
echo $exception;} it turns out to be *marginally* faster. Therefore, the only issue we need to work out is, what if what we're "try{}ing" can throw more than one exception? i.e. we're connecting to a DB, running a query, checking the result - thats 3 seperate errors. With the single class, we have one catch block. With the seperate classes, we need three catch blocks, or we need a parent class. Now, whilst we have a default parent class (Exception) catching all of these (or just our own parent class) means we need to do if ($exception instanceof Error17) which presumably will make it slower (not tested that far yet). But from my initial findings, I would say that by grouping errors into relevant single classes (either per package, or for each large procedure (i.e. user login)) is the fastest and most efficient way to do it. This is the first point I've disagreed with you upon Greg, I hope that cold hard facts will persuade you (and everyone else) that perhaps seperate classes is not the way to go. Certainly I hope this at least shows we need more testing before deciding which way to go. - Davey