in reply to Returning undef: The point I would like Damian to reconsider
I love perlmonks because it constantly reaffirms that there's always more than one way to do it. When you have a question, there's usually more than one 'right' answer. The question is: when I call some encapsulated piece of code, how will I know whether it succeeded or failed? Was there an error and what should I do?
The reason why I like the PBP 'rule' is because it's an easy to remember answer to a question that should be considered on every function call. Defensive programming means checking return values. The concept of what to return on failure is like a mini-protocol. "Use a bare return to return failure" is such an easy protocol....
For all the folks who think it's stupid, and hate the idea of typing 'return 1;', make up your own mini-protocol and a call it Perl's SecondBest Practices. LOL :-)
"Don't return undef when you mean an empty list" -- this is some serious wisdom, too. I'm really glad you said that. :-) I think it's worth mentioning that PBP also recommends using Contextual::Return to deal with that exact 'complication'.
IMO The Best Practice here is a combination of using "return;" anywhere something goes wrong and at the bottom of your subs using a block like this:
use Contextual::Return; sub items { ## Something failed! if ($failure) return; #TODO: Consider croaking! ## Being explicit! return ( LIST { qq(Item1 Item2) } HASHREF { {Item1 => 'big', Item2 => 'small'}} SCALAR { 2 } ); }
I think knowledge sharing and promoting 'the right way' is what will allow the Perl Community to continue to flourish. I think Damian was Noble in pursuing this ideal.
Kurt
Updated: Added points about Contextual::Return
|
|---|