Java – why would anyone construct a while loop like this?
I'm reading a book about Java. We're reading a ByteBuffer from a channel I found the author's way to construct an odd number of while loops:
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've tried this:
while(inCh.read(lengthBuf) != -1) {
It works the same way Is there a practical or code clear reason why the author will write it like him?
Solution
Obviously, your circular version is semantically the same However, this is not the only thing to consider
Note that there is a second condition below the while loop that breaks the loop I suspect that this is the reason for promoting the use of the author (true)
By writing it as while (true), you can remind readers that there must be one or more breakpoints inside Readers will have to look at breaks inside the loop and hope to find them
In your way, casual readers may scan the top of the code and assume that the while condition is the only way to terminate the loop
Another point to consider is symmetry or balance As the original author wrote, loop termination is the same form That is, breaking from within the cycle Your version feels asymmetrical One termination point in the while test and another termination point of different properties within the loop