If You're Looping, Look for a Better Way

by Larry Spencer Friday, April 5, 2013 3:43 PM

Today, it's more from the Code Review front. This is really the same point I made last time: Brevity is the Soul of Maintainability.

I just saw the following code in a review. It's part of a method whose input is a string called line. What do you think it does?


int verticalBarCount = 0;
string tempLine = line;
int off = tempLine.IndexOf('|');
while (off != -1)
    tempLine = tempLine.Substring(off + 1, tempLine.Length - (off + 1));
    off = tempLine.IndexOf('|');


After only a little head-scratching, and aided by the well-named variable, verticalBarCount, you probably surmised that the code counts the number of vertical bars in the input line. That's correct, and the code is correct. All well and good.

However, isn't this equally correct code a whole lot better?


int verticalBarCount = Regex.Matches(line, @"\|").Count;


The moral I'd like to draw from this vignette is: If you're looping, look for a better way. That's especially true if the loop is doing something low-level, like counting characters.

Tags: ,

All | General

About the Author

Larry Spencer

Larry Spencer develops software with the Microsoft .NET Framework for ScerIS, a document-management company in Sudbury, MA.