in reply to Code cleanup; how best to deal with: defined(%hash) is deprecated at...
After reading a ton of Perl code (much of it written by co-workers), I decided that the use of defined and exists can often be nearly random. Much less frequently but much more seriously, I've seen several cases of failures (some of them even in Production) caused by code like:
$foo->{gnarfle} = 'garthok' if defined $foo;
So I've instituted some simple best practices:
- Don't use defined (nor // nor //=) unless undef has a useful meaning (distinct from "just false").
- Don't use exists unless "missing", "undefined", and "false" all have distinct meanings (which is usually a bad idea).
- If 0 is a useful value and not "the default", then use a boolean test against length. (This ends up being pretty rare, though.)
- Otherwise (the large majority of the time), just use a simple boolean test (or || or ||=).
In particular, there is no such thing as a useful, false reference (unless you are overloading in a way that could return a false value -- and overloading is very rare in our code). So don't use defined (nor exists nor // nor //=) with references.
Somewhat related, for string-valued database columns, if the empty string doesn't have special meaning, then declare the column "not null default ''", so you don't have to deal with a random mix of NULL and '' values.
Similar to not using exists, don't check for missing positional parameters by checking the value of 0+@_ unless "missing", "undef", and "false" all have distinct meanings (which is usually a bad idea).
- tye
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Code cleanup; how best to deal with: defined(%hash) is deprecated at... (defined--)
by sundialsvc4 (Abbot) on May 22, 2014 at 11:01 UTC | |
by choroba (Cardinal) on May 22, 2014 at 11:21 UTC | |
by herveus (Prior) on May 22, 2014 at 15:58 UTC | |
by tye (Sage) on May 22, 2014 at 14:19 UTC | |
Re^2: Code cleanup; how best to deal with: defined(%hash) is deprecated at... (defined--)
by taint (Chaplain) on May 23, 2014 at 07:47 UTC | |
by boftx (Deacon) on May 24, 2014 at 08:32 UTC |