Sunday, October 20, 2013

Keep methods short

I was reading some code recently, and saw the notation of marking the beginning and end of loops (not the first time I've seen this).

for ( int i = 0; i < someEndVal; i++ ) { // begin myProcessingLoop
  // long set of steps here
} // endMyProcessingLoop

Why is that information there? Usually because the processing loop is so long that it doesn't fit on a single screen, or because there are so many nested loops that it is hard to decipher. Instead of commenting on the loops like that, rewrite the loops so they are short. A common technique is to extract the loop body into its own method.

for ( int i = 0; i < someEndVal; i++ ) {
    dostuff(i);
}

It removes the unnecessary comments and makes the code generally easier to read.

No comments:

Post a Comment