Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently. I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation. Essentially it uses a for loop to provide a kind of structured goto. My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.
ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.
Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses
boolean valid = false;
// this loop never loops
for (;;)
{
if (!condition1)
break;
condition2.setup();
if (!condition2)
break;
condition3.setup();
if (!condition3)
break;
valid = true;
break;
}
if (valid) dosomething();
EDIT:
I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.
The restructured code looks like this.
boolean valid = false;
breakout:
{
if (!condition1)
break breakout;
condition2.setup();
if (!condition2)
break breakout;
condition3.setup();
if (!condition3)
break breakout;
valid = true;
}
if (valid) dosomething();
Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?
I don’t think it’s the most readable way of doing it. Chained
if–else iflooks much better. But if you want to stick with it and don’t want to be so close to an infinite loop, you could do something like this: