Programming: describe loops by what happens inside, or by effect seen outside?

A general question about naming or commenting or defining loop structures in computer programming. Is it better practice to discuss a loop in terms of what happens inside it, once, when it operates? or by what happens as seen outside it when it runs multiple times?

Say you have a loop whose internal action lays a single brick, and you iterate this loop a thousand times to build a brick wall. Is it better to refer to the loop as the “lay a brick” loop, or as the “build a brick wall” loop?

I don’t think there’s really a correct answer here. I’d go with whichever description gives a better notion of what the loop does, which is probably generally the “build a brick wall” sort of description.

I suppose it depends on your house style. For me, though, it would make the most sense to put a comment outside the loop which documents what it does when it runs through all its iterations, and if necessary put other comments inside which document what it’s doing during each iteration.

Both. You’d call the procedure of the loop ‘Build a Brick Wall’ and the internal action ‘Lay a Brick’

Something like



PROCEDURE BuildAWall ()

   PROCEDURE LayABrick ()
   BEGIN
       DoStuff
   END

BEGIN
   LOOP (Whatever)
      LayABrick (Parameters)
   END LOOP
END


The actual names should be according to your internal house coding style.

I was always taught to label by what would be accomplished when the loop finished. That’s how you test it, put a breakpoint after the loop and test if what you said was going to happen actually happened. After that you can ignore what happens in the loop and just use the comment to follow the program. I guess if what’s in the loop is complex enough, you might comment that too, but then you might just stick it in it’s own appropriately named procedure. It’s a world of choice really.

Good. Thanks. This seems clear and reasonable. Where the loop is visible it’ll be named or commented according to the total result, and where its workings are visible they’ll be named or commented by their singlepass result. It’s a wallbuilder loop that has bricklaying methods inside. I like that.

There’s almost always something better about some approaches than others.