8

When do we use loop and a half? Also, should someone briefly elaborate how to write its code?

jdhao
  • 24,001
  • 18
  • 134
  • 273
aablah
  • 103
  • 1
  • 7
  • 13
    What do you even *mean* by "loop and a half"? I've never heard of the term before. – Jon Skeet May 26 '12 at 16:23
  • 3
    I googled "loop and a half" (which I didn't know either), and came up with this: http://www.cs.duke.edu/~ola/patterns/plopd/loops.html#loop-and-a-half, which explains what it is and when we use it. Google is your best friend. – JB Nizet May 26 '12 at 16:26
  • 4
    It seems someone puts a `break` in the middle of a loop and named it "loop and a half." – Alexander May 26 '12 at 16:27
  • 1
    I think the OP is about loop-and-a-half problem described in [this note](http://www.cis.temple.edu/~giorgio/cis71/software/roberts/documents/loopexit.txt). – Sergey Kalinichenko May 26 '12 at 16:27
  • Loop-and-a-Half Repetition Control, that's what's written in the book :/ Thanks dasblinkenlight :) – aablah May 26 '12 at 16:32

2 Answers2

11

You use loop-and-a-half to avoid repeating code from outside the loop to the inside. Example:

read a;
while a != b do
  stuff;
  read a;
end

becomes

while true do
  read a
  if a == b then break
  stuff;
end

Now I only have the read in one place.

stark
  • 12,615
  • 3
  • 33
  • 50
  • @Alexander that's how I would write the code normally. Its better to create a sub to avoid repeating code. But I do run into the loop and a half pattern fairly often. – stark May 26 '12 at 17:01
  • @Alexander That can't assign a new value to a (in Java that is), so that's probably not much of a help in real examples where stuff will probably want to access a. – Voo May 26 '12 at 17:21
  • @Voo, [really?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference) - anyways this most voted answer is not even Java though. – Alexander May 26 '12 at 20:44
  • @stark, that'd may be a `goto` tendency. – Alexander May 26 '12 at 20:46
  • 2
    @Alexander Yeah there's a **big** difference between changing internal state of an object and assigning a new object to a variable (yes I was quite careful when writing that sentence). Yes you can get around the limitation by creating wrapper objects, but that's not especially nice and only works if you control the whole stack - otherwise you also have to write lots of wrapper methods that take your wrapper objects to the real method and then change its state on return. – Voo May 26 '12 at 22:57
2

As an aside, I'd like to add that the scope of the variable (assuming a is a local variable in this idiom) is minimized as compared to the alternative case, where a is still in scope even after the while loop terminates. Minimizing the scope of local variables is considered good practice whenever possible (Josh Bloch, Effective Java, Item 45).

Dhruv Gairola
  • 9,102
  • 5
  • 39
  • 43