Please, please, please

rob_au on 2003-08-12T02:46:02

For all that we love about Perl, please, please, please check return values when calling functions and object methods. And if writing such code, please incorporate differing return values based upon execution success.

/me returns to code maintenance and debugging


Fatal

Juerd on 2003-08-12T08:21:59

And in case anyone thinks "it's just a one-time hack" and "this is just a proof of concept" are valid excuses: no, they're not!

If your code works, it will be used.

Make sure that it provides enough information to fix the problem when it stops working.

If you don't like checking return values (most of the time it's just a matter of adding "or die $!"), let something (or someone) do it for you.
use Fatal qw(:void open close);
open my $fh, $filename;
...
close $fh;

Don't return undef

pdcawley on 2003-08-12T11:36:53

Throw an exception. Any code I write for my own use is guaranteed to do one of three things:

1. Return $self
2. Return an 'interesting' value
3. Throw an exception

In general I'm slightly wary of object methods that return interesting values though, especially when those interesting values are simple attributes.

Re:Don't return undef

djberg96 on 2003-08-29T13:07:10

I had the same issue with Dave Cross' overloading article on perl.com. Relevant journal entry here.

Re:Don't return undef

gav on 2003-10-03T03:27:28

I like to return undef. It means you can do stuff like:
if (my $obj = Blah::Blah->fetch($foo)) {
    $obj->bar;
}

Re:Don't return undef

pdcawley on 2003-10-16T12:04:09

But that's an 'interesting value' in this context. Fetch should return the requested object or undef, and throw an exception on any other kind of failure.