Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

A couple questions about object oriented Perl programming: inheritance and error handling

by ted.byers (Scribe)
on Apr 17, 2013 at 19:20 UTC ( #1029204=perlquestion: print w/ replies, xml ) Need Help??
ted.byers has asked for the wisdom of the Perl Monks concerning the following question:

The first is probably the easiest. I am quite used to object oriented proramming in C++ (one of my favourite languages) and Java; and I have seen a number of different treatments of object oriented programming in perl, but have not seen anything yet about accessing data in a base class from the derived class). Nor have I seen anything especially useful in terms of multiple inheritance (something I keep to an absolute minimum in the other languages I use as far as is practicable). Can anyone point me to a thorough treatment of access to data in base classes, access control (what I have in mind is the Perl equivalent, if there is one, to private, protected and public access), and the complexities of multiple inheritance?

I am using my own access package to manage a user's authentication and authorization, and for the most part, this works beautifully. However, this is a web application, and I use the following for session management:

sub new { my $class = shift; my $query = shift; my $base = $query->url(-base => 1); my $cgi = $base; $cgi .= "/cgi-bin/"; my $self = {}; $self->{'base_url'} = $base; $self->{'rel_url'} = $query->url(-relative => 1); $self->{'cgi_url'} = $cgi; croak "Function new takes a an instance of class CGI as an argument +- dying a nasty death!\n" unless (defined $query); croak "Function new takes a an instance of class CGI as an argument +- dying a nasty death!\n" unless $query->isa('CGI'); my $session = shift; if ($session->is_expired()) { my $login_script = $base . "/login.html"; print $query->redirect($login_script); return; # exit(0); }

The usual call sequence is one creates a CGI object, and from that creates a CGI::Session object. Both are passed to function new, as the above code shows. After an object has been created, any number of other functions may be invoked before the cgi script exits. What happens is that when the user's session times out, he gets an error to the effect that we can't use the string "ERROR" as a HASH ref, while "strict refs" is use. I guess there are a couple things pertaining to this. The first involves what is the best practice for handling errors deep in the bowels of a package or object, about which the calling code ought to be blissfully ignorant. Is there, a way to detect an error condition within the classes member functions before doing what they are designed to do (so they can do nothing, except possibly log the error, if there is an error condition)? Or, is there something within Perl that serves the same requirements that C++ exceptions serve in C++. And the second is whether or not my redirection code shown above ought to be using exit in case of redirection instead of return, after the redirection header has been written.

Thanks

Ted

Comment on A couple questions about object oriented Perl programming: inheritance and error handling
Download Code
Re: A couple questions about object oriented Perl programming: inheritance and error handling
by NetWallah (Abbot) on Apr 17, 2013 at 21:20 UTC
    Re: Multiple Inheritance and Base Class access:

    These are covered in "perldoc perltoot" (Run at command line).
    See the sections titled "Multiple Inheritance", "Inheritance" and "Overridden Methods".

    These days, monks prefer to use "post-modern OO" implementations like Moose or it's minimalist imitation, "Moo".

    Re: Error handling

    You seem to be using CGI::Carp - if not, please do.
    That includes examples of globalized error handlers.

    Re: Redirection exit vs return

    I think exit is fine. Others may have esoteric reasons for preferring "return".

                 "I'm fairly sure if they took porn off the Internet, there'd only be one website left, and it'd be called 'Bring Back the Porn!'"
            -- Dr. Cox, Scrubs

      Others may have esoteric reasons for preferring "return".

      In a persistent environment, exit might not do what you want.

Re: A couple questions about object oriented Perl programming: inheritance and error handling
by stephen (Priest) on Apr 17, 2013 at 23:30 UTC

    Generally, it's a good idea to handle errors with block eval. In other words, if you do this:

    local $@; eval { # My code that can throw an error here might_throw_error(); }; if (my $exception = $@) { # Catch any error here. Error message in $@ warn "Caught random error: $exception\n"; } sub might_throw_error { # Flip a coin and throw an error if ( rand(1) > 0.5 ) { die "Random error!\n"; } }

    then you can put your error-handing and logging code in the "if" statement below. It will occasionally warn "Random error! at line X." If you want to rethrow the error, you can put "die" in the if statement.

    I generally don't think it's a good idea to call exit() in a constructor, or in anything other than the program's main routine. The best way to handle an error is to call die(). Then, if upper-level routines can handle the exception, they can do so with block eval as above. If you call exit(), there's no catching the exception. It makes it much more difficult to write unit tests for your code, for one thing.

    Is the error you're getting pointing to your own code, or code within CGI::Session? If it's your own code, you should use 'ref' to check to see if the variable you have is a string (which may be 'ERROR') or an object, then either renew the session or throw a more descriptive exception yourself with die(). Otherwise, you might want to use eval {} as above to catch the exception and handle it as you see fit.

    This is all pretty generic, since I'm not terribly clear on what's causing the exception. You might want to read Chapter 8 of chromatic's Modern Perl, which covers exceptions.

    Update:As Anonymonk points out below, block-eval error handling in perl has a number of edge cases. If possible you should use one of the many try-catch CPAN modules available. In addition to the ones he/she names, there's also TryCatch and Throwable.

    stephen

      $@ might not be a true value :) or other things, see Try::Tiny and Devel::EvalError for a description of the possible issue

      eval { execeptionalWithoutReturnValue(); 1; } or do { my $exception = $@; ... };

      Or

      use Try::Tiny;
      try {
        execeptionalWithoutReturnValue();
      } catch {
        warn "caught error: $_"; # not $@
      };
      

      Or

      use Devel::EvalError();
      my $ee = Deval::EvalError->new();
      $ee->ExpectOne(
          eval {
              execeptionalWithoutReturnValue();
              1;
          }
      );
      if( $ee->Failed() ) {    # if ( ! $ee->Succeeded() )
          ... $ee->Reason() ...;
      }
      

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1029204]
Approved by moritz
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2014-08-27 23:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (253 votes), past polls