Thread (2 messages) flat view 2 messages, 2 authors, 2016-06-15

Re: CodingGuidelines Perl amendment

From: demerphq <hidden>
Date: 2016-06-15 22:56:04

On 6 February 2013 17:29, Junio C Hamano [off-list ref] wrote:
Ted Zlatanov [off-list ref] writes:
quoted
 - As in C (see above), we avoid using braces unnecessarily (but Perl
   forces braces around if/unless/else/foreach blocks, so this is not
   always possible).
Is it ever (as opposed to "not always") possible to omit braces?
Only in a statement modifier.
It sounds as if we encourage the use of statement modifiers, which
certainly is not what I want to see.
As you mention below statement modifiers have their place. For instance

  next if $whatever;

Is considered preferable to

if ($whatever) {
  next;
}

Similarly

open my $fh, ">", $filename
   or die "Failed to open '$filename': $!";

Is considered preferable by most Perl programmers to:

my $fh;
if ( not open $fh, ">", $filename ) {
  die "Failed to open '$filename': $!";
}
You probably would want to mention that opening braces for
"if/else/elsif" do not sit on their own line,
and closing braces for
them will be followed the next "else/elseif" on the same line
instead, but that is part of "most of the C guidelines above apply"
so it may be redundant.
quoted
 - Don't abuse statement modifiers (unless $youmust).
It does not make a useful guidance to leave $youmust part
unspecified.

Incidentally, your sentence is a good example of where use of
statement modifiers is appropriate: $youmust is rarely true.
"unless" often leads to maintenance errors as the expression gets more
complicated over time, more branches need to be added to the
statement, etc. Basically people are bad at doing De Morgans law in
their head.
In general:

        ... do something ...
        do_this() unless (condition);
        ... do something else ...

is easier to follow the flow of the logic than

        ... do something ...
        unless (condition) {
                do_this();
        }
        ... do something else ...

*only* when condition is extremely rare, iow, when do_this() is
expected to be almost always called.
if (not $condition) {
  do_this();
}

Is much less error prone in terms of maintenance than

unless ($condition) {
  do_this();
}

Similarly

do_this() if not $condition;

leads to less maintenance errors than

do_this() unless $condition;

So if you objective is maintainability I would just ban "unless" outright.

Cheers,
Yves

-- 
perl -Mre=debug -e "/just|another|perl|hacker/"
Keyboard shortcuts
hback out one level
jnext message in thread
kprevious message in thread
ldrill in
Escclose help / fold thread tree
?toggle this help