A question of Style, was: SPUG: Sort an array question

Brian Hatch spug at ifokr.org
Fri Dec 27 12:35:26 CST 2002

> 	In my opinion one of the biggest things that promotes readability is the
> use of long variable names.  Since when I program I spend far more time
> sitting and thinking about how I want the program to work than I do actually
> typing things in, using short variable names ($i, etc.) seems like
> optimizing for speed of typing over ease of programming (readability).  That
> seems a bit backward to me.

This is true in general, but there are many cases where a short
name is a good choice.  $i or $j are commonly used to indicate
'index into an array', and that's just what was used in the example

	for( $i = 0; $i <= $#array; $i++ ) {
	    for( $j = $i+1; $j <= $#array; $j++ ) {
		$tmp = $array[$j] . $array[$i];	  # join compare elements

You could call them 'index1' and 'index2' but that actually makes
the code less readable, as the name takes up too much space
to make it harder to read the 'jist' of things - comparing
values inside @array.

I have no problem with short names when they have a very short
life expectancy.  For example I'd have written the above as

	for my $i ( 0 .. $#array) {
	    for my $j ( $i+1 .. $#array) {
		$tmp = $array[$j] . $array[$i];	  # join compare elements

Why?  $i and $j are scoped only inside this block.  No short names
should be globally scoped - makes it too hard to remember what
they're used for.  (It's also more readable than the traditional
3-part for loop.  Yes, the above is actually a foreach loop,
but I am too lazy to type the four extra characters if perl
doesn't care.)

Brian Hatch                  "That was the law, as set down by Valen.
   Systems and                Three castes: worker, religious, warrior.
   Security Engineer          They build, you pray, we fight."

Every message PGP signed
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 240 bytes
Desc: not available
Url : http://mail.pm.org/archives/spug-list/attachments/20021227/47944dd3/attachment.bin

More information about the spug-list mailing list