Under what circumstances are you likely to get an error from:$thing->do_something;?
If you create $thing, and you error checked that creation my $thing = Some::Class->new(...) or die;, this can't happen.
If your code is passed $thing and you validated your inputs:
sub SomeSubOrMethod { my $thing = shift; croak 'Bad param' unless $thing and ref $thing; ...
This can't happen.
If new() or similar constructor returns a non-ref or non-blessed ref, it is a fundamental coding error that will be discovered the first time class is used. Even the simplest of tests, during the development of the bad class, or when you first try to use that class will detect this. It couldn't possibly make it into production unless you are in the habit of putting code that has never even been run into production.
If you created $thing yourself, then you know what class it is, so you'll know what methods it has. Your testing should be sufficient to detect any such typos long before they become a production problem.
If you are passed $thing, and you've validated your inputs, then you've ensured that it is of a type that you can reasonably expect to have a do_something method.
In short. DON'T perform such checks. Allow them to fail immediately and loudly.
This will ensure that if the circumstances arise, the clearest possible indication of what has gone wrong is given to the programmer who a) typoed the method name (usually you); or b) passed your code a non-reference, or reference to the wrong class of object.
The alternatives are:
Can you give a better error message than croaking with trace back?
Call a different method? Pretend you didn't need to call that method?
In the end, even if you perform your blow by blow validation every time before you call a method--besides the horrible performance penalty you impose--there is no guarantee that the do_something method:
In vast majority of cases, the method will exist and do what is required. In the remaining percentage of cases, there's nothing you can reasonably do about it. So, just get on with it and let it fail on those rare occasions when it will.
In reply to Re: Error handling in chained method calls
by BrowserUk
in thread Error handling in chained method calls
by szabgab
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |