Note that there are some explanatory texts on larger screens.

plurals
  1. POBetter way to structure/new keyword
    text
    copied!<p>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. </p> <p>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.</p> <p>Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses</p> <pre><code>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(); </code></pre> <p>EDIT:</p> <p>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.</p> <p>The restructured code looks like this.</p> <pre><code>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(); </code></pre> <p>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?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload