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

科技回声

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

GitHubTwitter

首页

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

资源链接

HackerNews API原版 HackerNewsNext.js

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

Ask HN: What’s the Point of “Else”?

2 点作者 wideareanetwork大约 4 年前
Is there any point to the else after an if?<p>Why do we need else?<p>Can’t we chuck it away?<p>Does else serve a purpose?<p>NOTE: I’m not talking ternaries. Ternaries are super useful.

3 条评论

hgsv大约 4 年前
Technically, we probably could, but would often need workarounds for code which changes the initial condition such as,<p><pre><code> i = 0 if i &lt;= 0: i += 1 else: i -= 1 </code></pre> You could of course solve this in various ways, for example something like:<p><pre><code> condition = i &lt;= 0 if condition: i += 1 if not condition: i -= 1 </code></pre> But i don&#x27;t find that to read as well as an else block. Also restating longer conditions which we don&#x27;t change in the then-block to mimic an else with an if seems like a waste of spacetime.
jfengel大约 4 年前
All syntax is about what&#x27;s convenient for people to structure their world. If it weren&#x27;t, we&#x27;d all just be writing machine code.<p>The word &quot;else&quot; exists in every human language, implying that people have a thought pattern for &quot;if this then that, otherwise the other thing&quot;. Structuring code is hard enough, so taking cues from human language is a good heuristic.<p>If&#x2F;else is side-effecty. Ternaries are the equivalent in a functional world. Some code is very natural in a functional style, but statefulness is another natural way for people to work. Every time you write intermediate results on scratch paper, you&#x27;re doing stateful thinking. Every time you make a decision and take an action that can&#x27;t be undone, that&#x27;s stateful thinking.<p>There are some purely side-effect-free languages, but many developers find them unnatural. At the very least it requires a substantial revamping to think about databases and UIs in a purely stateless way. And if you&#x27;re working in a stateful language, if&#x2F;else is a natural way to express some actions.<p>People are increasingly pushing toward functional programming, and the more you do that, the fewer else statements you write. In fact, the fewer if statements you write as well. If statements are kind of a code smell -- and in fact, ifs without elses are also a code smell. They hint at asymmetry, and there&#x27;s a hidden &quot;don&#x27;t do anything&quot; that should make you wonder if you should have done something.
brudgers大约 4 年前
I imagine a headline:<p><pre><code> The surprising results of dropping else from ifs </code></pre> Programs are mostly for humans to read.