Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: String equality and undef

by webfiend (Vicar)
on Dec 09, 2008 at 14:28 UTC ( #729181=note: print w/replies, xml ) Need Help??

in reply to String equality and undef

If you follow the very good advice of using defined as the test, you might also want to switch the ordering of your if/else logic. Instead of

if (!defined $id) { # Deal with id } else { # Deal with not undef id }

you might want to consider

if (defined $id) { # Deal with a defined id } else { # Deal with an undefined id }

It's just personal aesthetics. The first form ("if not" / "else") sounds awkward to me compared to "if" / "else".

Replies are listed 'Best First'.
Re^2: String equality and undef
by kyle (Abbot) on Dec 09, 2008 at 15:42 UTC

    On the other hand, dealing with a bogus value is usually shorter than what you do with a real value, and I think a good style guideline is to keep "else" as close as possible to the condition it negates.

    if ( ! defined $id ) { die "Why is this ID not defined?" } else { # Twenty # or # more # lines }

    I like this guideline because I've too many times found myself looking at a screen of code like this:

    # blah # blah } else { return undef; } } else { unlink $tmpfile; return undef; }

    What were the conditions?

    Even better in this case would have been an early return so as to avoid the extra level of indent anyway, but that's beside the point.

      Fair point, but you don't really need to worry about the else when your reaction to the if condition is death.

      unless ( defined $id ) { die "Why is this ID not defined?"; } # Life goes on normally for everyone else.

      And I disagree with your closing, an early return in cases like that is exactly the point. You want to take any steps you can to make the code more readable, especially if it means completely ignoring my initial "switch the logic" comment.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://729181]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2019-07-16 04:32 GMT
Find Nodes?
    Voting Booth?

    No recent polls found