Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I wouldn't say it's <em>bad</em> - but equally I would normally at least look for an alternative.</p> <p>In situations where it's the first thing I write, I almost always at least <em>try</em> to refactor it into something clearer. Sometimes it can't be helped (or the alternative is to have a <code>bool</code> variable which does nothing meaningful except indicate the end of the loop, less clearly than a <code>break</code> statement) but it's worth at least trying.</p> <p>As an example of where it's clearer to use <code>break</code> than a flag, consider:</p> <pre><code>while (true) { doStuffNeededAtStartOfLoop(); int input = getSomeInput(); if (testCondition(input)) { break; } actOnInput(input); } </code></pre> <p>Now let's force it to use a flag:</p> <pre><code>boolean running = true; while (running) { doStuffNeededAtStartOfLoop(); int input = getSomeInput(); if (testCondition(input)) { running = false; } else { actOnInput(input); } } </code></pre> <p>I view the latter as more complicated to read: it's got an extra <code>else</code> block, the <code>actOnInput</code> is more indented, and if you're trying to work out what happens when <code>testCondition</code> returns <code>true</code>, you need to look carefully through the rest of the block to check that there isn't something <em>after</em> the <code>else</code> block which would occur whether <code>running</code> has been set to <code>false</code> or not.</p> <p>The <code>break</code> statement communicates the intent more clearly, and lets the rest of the block get on with what it needs to do without worrying about earlier conditions.</p> <p>Note that this is exactly the same sort of argument that people have about multiple return statements in a method. For example, if I can work out the result of a method within the first few lines (e.g. because some input is null, or empty, or zero) I find it clearer to return that answer directly than to have a variable to store the result, then a whole block of other code, and <em>finally</em> a <code>return</code> statement.</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