PBP: 084 Loop Labels

The PBP suggests applying a label to each loop that is exited explicitly.  A simple request, but one I usually find vexing.

Until a week or two ago, I would have said I refused to follow this practice.  I would have told you labels are ugly, unusual, and should only be in the code when needed.  I would have been self-righteous and indignant about it, and it would have been a fine rant.

However, since then I have seen several places where the addition of the label made things a lot clearer.  There was no ambiguity to the compiler, but my human brain benefited from the addition of an extra noun there to tell me what the heck we were nexting.

In fact, the example provided for Distributed Control was one such place.  The addition of a single word in the example code made it clearer what was happening.

I have spent a lot of time grumbling at Perl Critic about this requirement, feeling it was a waste of time and effort, something you did by rote to shut up the inordinately picky machine.  The thing that led me to work that way was badly chosen loop labels.  Picking names like “LOOP” helps no one, just like using $i as an iterator isn’t all that helpful.  (I always felt “i” for “iterator” was named after the fact.  The collection of other things like j, k, foo, bar, and baz, aren’t very helpful.  Those are tolerable as metasyntactic variables, but I see them far more frequently.)

So, pick good names, and this helps your code.  Too bad names are hard.  Do it anyway.

The extremely comprehensive examples in the book offer some other plausible reasons, most of which deal with highly complex loop interactions and moving code around.  There is value there, but I never felt it worth the trouble, and that it made the code noisy and distracting for a return that happened only rarely.  They’re not bad reasons, they’re just not compelling to me.  Given them with the “make code clear” and I find it a much more concrete argument!

One Response to “PBP: 084 Loop Labels”

  1. James Morgan says:

    The i comes to us from FORTRAN, a language that in it’s early days was primarily written on punch cards, which could make short variable names a significant benefit. FORTRAN also had the odd behavior that the first character of a variable name would define it’s type. The letters I through N were all integers. So it was common to reserve the single letter names for commonly reused concepts, and the first integer available to use is i. Same with j and k, they are just the next letters in the one character integers.

    Any attempt to make $i mean iterator (I’ve also heard index, since it’s common to loop over arrays) is backwards justification for ‘but we always did it that way’ behaviors. I would accept that i stands for integer, that seems some what likely, but not useful. In Perl I use $idx if I mean array index for a loop, or another reasonable name if it’s not.

Leave a Reply