Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would someone structure a while loop like this?

Tags:

java

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?

like image 211
Steve M Avatar asked Feb 26 '26 21:02

Steve M


1 Answers

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.

like image 76
David Heffernan Avatar answered Mar 01 '26 10:03

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!