The problem of design unless in Perl

In the Perl programming language, as in many other programming languages have design if:

▶ Run
#!/usr/bin/perl

my $value;

if (!defined $value) {
    print 'value must be defined';
}

Body if is performed if the condition returns true.

But, in addition to design if even has a reverse design unless. Body unlessruns if the condition returns false. Here's the code that works exactly the same as the previous one, but written using unless:

▶ Run
#!/usr/bin/perl

my $value;

unless (defined $value) {
    print 'value must be defined';
}

If you look at these two examples, we see that when using unless , the code uses less structures (does not have to write !), but the code is longer than 3 characters.

In addition I have more to print, when you use unless may have one problem. Imagine that we need to Supplement our code with unless. Now he performs some actions when a variable $value is undef. Did the task to perform an action in the case of a reverse situation — when $value is anything but undef. Quite natural the reaction in this situation is to add elseunit:

▶ Run
#!/usr/bin/perl

my $value;

unless (defined $value) {
    print 'value must be defined';
} else {
    print 'value is defined';
}

It turned out working code and this code was easy to write, but it turned out bad code. This code is hard to fix and understand. Instead, the code would have to write directly:

▶ Run
#!/usr/bin/perl

my $value;

if (defined $value) {
    print 'value is defined';
} else {
    print 'value must be defined';
}

Unfortunately, if the original code uses unless, then there is a great temptation not to change it to if, and just write else. But it turns out bad code.

It is believed that the ability to write unless-else is generally a mistake in the language design. And such the design should fail, instead of working.

unless, as well as if can be used in Postfix form:

▶ Run
#!/usr/bin/perl

my $value;

print 'value must be defined' unless defined $value;

When you use Postfix notation unless problems unless-else does not occur, as in this version else generally nowhere to enter.

Total recommendation. Never use the design unless ( $bool ) { ... }, as it leads to the deterioration of the readability of the code. About the use of unless a Postfix variant of this strict recommendation no. To use or not Postfix unless it is a matter of agreement in the team and a matter of taste. The author prefers never do not use unless.

Other articles

Comments