While loop with inner assignments causing checkstyle errors

Viewed 2171

I'm going through my code to make sure it conforms to CheckStyle standards.

I personally feel that the rule "No Inner Assignments" makes the code more complicated to understand (you have to look in 3 places instead of 1).

Is there some way that I could preserve my single area by creating a {} block within the while loop to perform my assignments and return a boolean?!

What are your opinions?

File file = new File("C:\\test.txt");
FileInputStream fileInputStream = new FileInputStream(new FileInputStream(file));

// Inner Assignment
while ((int i = fileInputStream.readLine()) != -1)
{
  //
}

// No Inner Assignment
int i = fileInputStream.readLine();
while(i!= -1)
{
  //
  i = in.readLine();
}

I encounter similar issues when I require a while loop which assigns a combination of some variable using, for example the ++ operator.

Would this for loop be considered a better alternative (it does comply with checkstyle)

for (int i = fileInputStream.readLine(); i != -1; i = fileInputStream.readLine())
{
  //
}
1 Answers

You can rewrite your loop as an infinite loop with a break in the middle, like this:

while(true) {
    int i = fileInputStream.readLine();
    if (i == -1) break;
}

Note that i can be moved inside the loop: the only value that it can have upon exiting the loop is -1, so there is no reason to keep the variable visible outside the loop.

Related