I want to refactor the following code because I don't feel comfortable about using assignment inside comparison operator. It looks like pretty idiomatic C, but do you think this is a good practice in Java?
private void demoA(BufferedReader reader) throws IOException {
String line = null;
while ((line = reader.readLine()) != null) {
doSomething(line);
}
}
Here is an alternative.
private void demoB(BufferedReader reader) throws IOException {
String line = reader.readLine();
while (line != null) {
doSomething(line);
line = reader.readLine();
}
}
UPDATE: I've stumbled across a similar question asked couple years ago. It seems that opinions on whether it's OK or not are divided. However, both Guava and Commons IO provide alternative solutions for this issue. If I had any of these libs in the current project, I'd probably use them instead.
reader.readLine();
should beline = reader.readLine();
? \$\endgroup\$demoA
to be idiomatic for Java. That said, there's an old SO question on the same topic: stackoverflow.com/questions/4677411/… Especially the highest-rated (not accepted) answer is interesting. \$\endgroup\$String line = null;
butString line;
. \$\endgroup\$