Reputation: 9784
I'm reading a book on Java, and we're on reading from a channel into a ByteBuffer. I found the way the author was structuring the while loop odd:
try (FileChannel inCh = (FileChannel) Files.newByteChannel(file)) { ByteBuffer lengthBuf = ByteBuffer.allocate(8); int strLength = 0; ByteBuffer[] buffers = { null, ByteBuffer.allocate(8) }; while(true) { if(inCh.read(lengthBuf) == -1) break; lengthBuf.flip(); strLength = (int)lengthBuf.getDouble(); buffers[0] = ByteBuffer.allocate(2*strLength); if(inCh.read(buffers) == -1) { System.err.println("EOF found reading ht eprime string."); break; } System.out.printf("String length: %3s String: %-12s Binary Value: %3d%n", strLength, ((ByteBuffer) (buffers[0].flip())).asCharBuffer().toString(), ((ByteBuffer)buffers[1].flip()).getLong()); lengthBuf.clear(); buffers[1].clear(); } System.out.println("\nEOF reached."); } catch (IOException e) {
I tried it like this:
while(inCh.read(lengthBuf) != -1) {
and it works the same. Would there be a practical or code clarity reason the author would write it like he did?
Upvotes: 3
Views: 212
Reputation: 612884
It is clear that your version of the loop is semantically identical. However, that's not the only thing to consider.
Notice that further down the while
loop there is a second condition that breaks out of the loop. I suspect that this is what has motivated the author to use while (true)
.
By writing it as while (true)
you alert the reader to the fact that there must be one or more breaks inside the while
. The reader is going to have to look inside the loop for breaks, and will hopefully find them both.
Written your way, the casual reader might scan the top of the code and assume that the while
condition was the only way for the loop to terminate.
Another point to consider is that of symmetry, or balance. As written by the original author, the loop terminations are all of the same form. Namely breaks from within the loop. Your version feels asymmetrical. One termination point in the while
test, and a further termination point, of a different nature, inside the loop.
Upvotes: 10
Reputation: 2833
The author has two exit points, one of which prints out an error before exiting the loop. Just makes the code a little more verbose in that case. It can be written in a number of different ways of course.
Upvotes: 2