Should a Perl constructor return an undef or a “invalid” object?

后端 未结 4 1726
南旧
南旧 2021-02-14 10:06

Question:

What is considered to be \"Best practice\" - and why - of handling errors in a constructor?.

\"Best Practice\" can b

4条回答
  •  情话喂你
    2021-02-14 10:44

    I would recommend against #1 simply because it leads to more error handling code which will not be written. For example, if you just return false then this works fine.

    my $obj = Class->new or die "Construction failed...";
    

    But if you return an object which is invalid...

    my $obj = Class->new;
    die "Construction failed @{[ $obj->error_message ]}" if $obj->is_valid;
    

    And as the quantity of error handling code increases the probability of it being written decreases. And its not linear. By increasing the complexity of your error handling system you actually decrease the amount of errors it will catch in practical use.

    You also have to be careful that your invalid object in question dies when any method is called (aside from is_valid and error_message) leading to yet more code and opportunities for mistakes.

    But I agree there is value in being able to get information about the failure, which makes returning false (just return not return undef) inferior. Traditionally this is done by calling a class method or global variable as in DBI.

    my $dbh = DBI->connect($data_source, $username, $password) or die $DBI::errstr;

    But it suffers from A) you still have to write error handling code and B) its only valid for the last operation.

    The best thing to do, in general, is throw an exception with croak. Now in the normal case the user writes no special code, the error occurs at the point of the problem, and they get a good error message by default.

    my $obj = Class->new;
    

    Perl's traditional recommendations against throwing exceptions in library code as being impolite is outdated. Perl programmers are (finally) embracing exceptions. Rather than writing error handling code ever and over again, badly and often forgetting, exceptions DWIM. If you're not convinced just start using autodie (watch pjf's video about it) and you'll never go back.

    Exceptions align Huffman encoding with actual use. The common case of expecting the constructor to just work and wanting an error if it doesn't is now the least code. The uncommon case of wanting to handle that error requires writing special code. And the special code is pretty small.

    my $obj = eval { Class->new } or do { something else };
    

    If you find yourself wrapping every call in an eval you are doing it wrong. Exceptions are called that because they are exceptional. If, as in your comment above, you want graceful error handling for the user's sake, then take advantage of the fact that errors bubble up the stack. For example, if you want to provide a nice user error page and also log the error you can do this:

    eval {
        run_the_main_web_code();
    } or do {
        log_the_error($@);
        print_the_pretty_error_page;
    };
    

    You only need it in one place, at top of your call stack, rather than scattered everywhere. You can take advantage of this at smaller increments, for example...

    my $users = eval { Users->search({ name => $name }) } or do {
        ...handle an error while finding a user...
    };
    

    There's two things going on. 1) Users->search always returns a true value, in this case an array ref. That makes the simple my $obj = eval { Class->method } or do work. That's optional. But more importantly 2) you only need to put special error handling around Users->search. All the methods called inside Users->search and all the methods they call... they just throw exceptions. And they're all caught at one point and handled the same. Handling the exception at the point which cares about it makes for much neater, compact and flexible error handling code.

    You can pack more information into the exception by croaking with a string overloaded object rather than just a string.

    my $obj = eval { Class->new }
      or die "Construction failed: $@ and there were @{[ $@->num_frobnitz ]} frobnitzes";
    

    Exceptions:

    • Do the right thing without any thought by the caller
    • Require the least code for the most common case
    • Provide the most flexibility and information about the failure to the caller

    Modules such as Try::Tiny fix most of the hanging issues surrounding using eval as an exception handler.

    As for your use case where you might have a very expensive object and want to try and continue with it partially build... smells like YAGNI to me. Do you really need it? Or you have a bloated object design which is doing too much work too early. IF you do need it, you can put the information necessary to continue the construction in the exception object.

提交回复
热议问题