Monday, January 02, 2006

Design by Analogy

Here's a function that's in almost every shell script I write:
die() {
echo $* >&2 ; exit -1;
}
The syntax is straightforward and obvious. $* is the list of
arguments passed to die() by the caller. The call

die "usage: foobar mumble frabitz"
spits a usage message to stderr and then ends the program.

Why call it "die()"? Because that's what the corresponding Perl
function is called.

Designing things to mimic one another is a good habit. To link
bar to foo, do you say ln foo bar or
ln bar foo? It's easier to remember once you know that cp,
mv, and ln all use the same argument order. Similarly, once you
know rm -i, you're more likely to guess that cp -i,
mv -i, and ln -i all work, too.

The drawback is that you need to remember that the copy isn't exactly the same
as the original. For example, Perl's die() spits out additional
information unless the argument string ends with a carriage return. In
practice, I don't find this a disadvantage. If you do, you could name yours
s.die() or something.

For example, $* in a function is all the args to a function; in a
shell script, it's all the args to the script. $1, $2, etc.
are the individual args to a script. Guess what $1 is inside a
function.

But don't just guess. Try it. And try writing a warn() function to
mimic Perl's. If you don't know Perl, try writing a shell analogue to some
other useful thing you know from another language.

0 Comments:

Post a Comment

<< Home