TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Ditch That Else

3 点作者 p5v超过 1 年前

2 条评论

Someone超过 1 年前
If possible, also ditch that <i>if</i>.<p>Swift replaces it by <i>guard</i>. I’m not a 100% fan of its syntax (1), which is<p><pre><code> guard &lt;#condition#&gt; else { &lt;#statements#&gt; } </code></pre> but do like that <i>&lt;#statements#&gt;</i> <i>must</i> return. So, <i>guard… else</i> semantically can be replaced by <i>if !</i>, but is a bit more limited, thus making it easier to recognize the pattern.<p><a href="https:&#x2F;&#x2F;docs.swift.org&#x2F;swift-book&#x2F;documentation&#x2F;the-swift-programming-language&#x2F;statements&#x2F;" rel="nofollow noreferrer">https:&#x2F;&#x2F;docs.swift.org&#x2F;swift-book&#x2F;documentation&#x2F;the-swift-pr...</a>:<p><i>“The else clause of a guard statement is required, and must either call a function with the Never return type or transfer program control outside the guard statement’s enclosing scope using one of the following statements:<p>- return<p>- break<p>- continue<p>- throw”</i><p>(1) I can’t think of a much better one, but think I would have picked<p><pre><code> requires &lt;#condition#&gt; else { &lt;#statements#&gt; } </code></pre> or (getting rid of that weird <i>else</i>):<p><pre><code> ifnot &lt;#condition#&gt; { &lt;#statements#&gt; } </code></pre> Eiffel’s preconditions (<a href="https:&#x2F;&#x2F;www.eiffel.org&#x2F;doc&#x2F;eiffelstudio&#x2F;Precondition" rel="nofollow noreferrer">https:&#x2F;&#x2F;www.eiffel.org&#x2F;doc&#x2F;eiffelstudio&#x2F;Precondition</a>) look even nicer:<p><pre><code> require &lt;#condition#&gt; </code></pre> but do not allow specifications of what to do when the condition isn’t met, and aren’t supposed to be checked in procession code. <a href="https:&#x2F;&#x2F;www.eiffel.org&#x2F;doc&#x2F;eiffel&#x2F;ET-_Design_by_Contract_%28tm%29%2C_Assertions_and_Exceptions" rel="nofollow noreferrer">https:&#x2F;&#x2F;www.eiffel.org&#x2F;doc&#x2F;eiffel&#x2F;ET-_Design_by_Contract_%28...</a>:<p><i>“It is in fact part of the Eiffel method that a routine body should never test for the precondition, since it is the client&#x27;s responsibility to ensure it. (An apparent paradox of Design by Contract™, which is reflected in the bottom-right entries of the preceding and following contract tables, and should not be a paradox any more at the end of this discussion, is that one can get more reliable software by having fewer explicit checks in the software text.)”</i>
danjc超过 1 年前
Great advice. This is probably one of the top 5 or 10 things an inexperienced programmer could adopt to level up.