Monday, April 28, 2008

Too smart or too novice in Java: Relevance of for loops

During the course of my work, I have had to fix some code written by others and modify existing code for enhanced functionality. In one of such projects, I encountered this piece of code written by someone


for(boolean valid = false; !valid; valid = true)
{
try
{
sp = spf.newSAXParser();
parser = new ProjectParser();
sp.parse(projectFile, parser);
}
catch(Exception e)
{
e.printStackTrace();
log.throwable(e);
throw new RuntimeException((new StringBuilder("Unable to parse ")).append(projectFile.getAbsoluteFile()).toString());
}
}


Let's see how this for loop works. It initializes a boolean called valid with a value false. The condition is until valid is false. The increment is making valid true. And then inside the loop, the coder wants to accomplish something. Now what is the point of this for loop at all. Was the for loop used because the coder didn't know that loops are used for, you guessed right, looping. If he/she just wanted it to run only once, then what is the point of using a for loop at all. How different is the below code from the above code.


try
{
sp = spf.newSAXParser();
parser = new ProjectParser();
sp.parse(projectFile, parser);
}
catch(Exception e)
{
e.printStackTrace();
log.throwable(e);
throw new RuntimeException((new StringBuilder("Unable to parse ")).append(projectFile.getAbsoluteFile()).toString());
}


This would execute the code only once and that is the desired behavior that was accomplished by using the for loop for once. I think keeping your code clean and staying away from such unnecessary stuff helps you in keeping your code clean and reducing any unwanted bugs. Why turn the hand around the neck to eat something when you could directly eat it.. Is this trying to be too smart or being too much of a novice to know what loops are used for. Or is there something, that I am missing that is something great that I haven't realized in using this type of code. If someone could elaborate, I would be glad...

1 comment:

JP said...

Sagaar,

Good blog.Keep it up!!!.

Hey you are right! Not sure what is the purpose of for loop.

Thanks
Prashant
http://prashantjalasutram.blogspot.com/