Stop using nested ifs. Do this instead

<p>A typical use case for nested ifs: you want to perform all sorts of checks on some data to make sure it&rsquo;s valid before finally doing something useful with it.</p> <p>Don&rsquo;t do this! :</p> <pre> // JavaScript function sendMoney(account, amount) { if (account.balance &gt; amount) { if (amount &gt; 0) { if (account.sender === &#39;user-token&#39;) { account.balance -= amount; console.log(&#39;Transfer completed&#39;); } else { console.log(&#39;Forbidden user&#39;); } } else { console.log(&#39;Invalid transfer amount&#39;); } } else { console.log(&#39;Insufficient funds&#39;); } }</pre> <p>There&rsquo;s a better way:</p> <pre> // JavaScript function sendMoney(account, amount) { if (account.balance &lt; amount) { console.log(&#39;Insufficient funds&#39;); return; } if (amount &lt;= 0) { console.log(&#39;Invalid transfer amount&#39;); return; } if (account.sender !== &#39;user-token&#39;) { console.log(&#39;Forbidden user&#39;); return; } account.balance -= amount; console.log(&#39;Transfer completed&#39;); }</pre> <p>See how much cleaner it is? Instead of nesting ifs, we have multiple if statements that do a check and&nbsp;<code>return</code>&nbsp;immediately if the condition wasn&#39;t met. In this pattern, we can call each of the&nbsp;<code>if</code>&nbsp;statements a&nbsp;<strong>guard</strong>&nbsp;<strong>clause</strong>.</p> <p>If you do a lot of Node.js, you&rsquo;ve probably seen this flow in Express middleware:</p> <p><a href="https://medium.com/coding-beauty/stop-using-nested-ifs-ed30e5ea5086"><strong>Click Here</strong></a></p>
Tags: Java nested