http://www.perlmonks.org?node_id=265228


in reply to chaining method calls

The only real problem I have with it is that error checking (or debugging) can be a pain, as you noted. (update: That is, doing "nice" error checking doesn't allow this while debugging with it is confusing.)

But the solution to that is to have these methods, on failure, return an "error object" that uses AUTOLOAD to return itself no matter what method gets called on it, in a string context gives back the descriptive error that it was created with (which should include method names and line numbers and such), in a boolean context returns a false value, and, if it gets destroyed without having been used in a boolean or string context, it dies with the descriptive error.

I been wanting to write that "error object" for a few years now. (: Just haven't found the time/motivation/prioritization. ):

                - tye
  • Comment on Re: chaining method calls (smart error object)

Replies are listed 'Best First'.
Re: Re: chaining method calls (smart error object)
by Ovid (Cardinal) on Jun 11, 2003 at 23:42 UTC
Re: Re: chaining method calls (smart error object)
by submersible_toaster (Chaplain) on Jun 12, 2003 at 06:56 UTC

    I like your idea, enough even to have a bash at it myself, moreso for educational purposes than anything. The first thing that struck me thought was "How can AUTOLOAD determine boolean context?". I know that wantarray will define whether the calling context is list, scalar or void. However I am stumped when it comes to determining boolean context.

    If I have you right.., and Some::Package returns error objects on failure.

    my $obj = Some::Package->new( %params ); $obj->connect()->synchronise()->disconnect();
    Presuming the new method fails, returning an error object (populated with some meaningful message), then the call to connect will be caught by the error object's AUTOLOAD. At this point we determine context, and depending on that confess.

    Is there nothing already out-there to do this? I'm off to CPAN first. ++tye


    I can't believe it's not psellchecked
      The first thing that struck me thought was "How can AUTOLOAD determine boolean context?".

      AUTOLOAD doesn't have to. You overload bool and use it to set some internal flag in the object to say it's been evaluated in a boolean context. Then in DESTROY you throw an exception if the flag has not been set.