The first metric to look for is conciseness. How many lines of code does it take to express a concept? For example, swapping a two variables. In most languages, you have to use an explicit temp variable, such as in the following C code:
temp = i;
i = j;
j = temp;
That's three lines to express a single concept. Most imperative languages require the same thing. Perl (and similar languages like Python and Ruby) does it in one.
( $i, $j ) = ( $j, $i );
Two lines doesn't sound like much. But, think about it as a 3-to-1 reduction. That means 300 lines is now 100. Ohhhh.
I find this a spurious example, because I'm not aware of any real situations (in well written code) in which you'd want to swap variables :)
ReplyDeleteAdamKennedy, have you considered sorting algorithms?
ReplyDeleteThis might not be the best example for concision because it's the lack of a temp that's the real win. That is, the Perlish code isn't better just because it's shorter; it's really better because it doesn't create another variable. We didn't just save 200 lines, we saved 100 temporary variables. Or worse, the same variable scoped globally (or, at least, wider than necessary) reused 99 more times.
ReplyDeleteWell, if all you are concerned with is the extra variable you can say
ReplyDeletea ^= b;
b ^= a;
a ^= b;
Humorously, this even works on strings in Perl:
#!/usr/bin/perl
use strict;
use warnings;
my $x = "foo";
my $y = "quux";
$x ^= $y;
$y ^= $x;
$x ^= $y;
print "x $x y $y\n";