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

科技回声

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

GitHubTwitter

首页

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

资源链接

HackerNews API原版 HackerNewsNext.js

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

Stop Abusing the JavaScript Ternary Operator

5 点作者 karthikksv大约 12 年前

2 条评论

gruseom大约 12 年前
On the contrary. I prefer<p><pre><code> for (var i = 0; i &#60; arr.length; i++) { arr[i] = foo(i) ? bar(i) : baz(i); } </code></pre> to<p><pre><code> for (var index = 0; index &#60; array.length; index++) { if (foo(index)) { array[index] = bar(index); } else { array[index] = baz(index); } } </code></pre> in every way, including for readability.<p>The example is trivial but instructive. Each line in the second version is arguably more readable (in isolation) than its counterpart in the first, yet the verbose version as a whole imposes a longer time-to-comprehension on the reader — especially if you allow for the ability to grok idioms at a glance that one inevitably acquires after working with a given language or system for some time.<p>In my experience this argument becomes increasingly compelling as one applies it to more complex programs. What the naive notion of "readability" fails to account for is the compounding complexity tax of verbosity. It's a bit like analyzing the profitability of a trading system without considering transaction costs.<p>One more thing, with apologies for this being patronizing: an infatuation with an explicit spell-everything-out standard of readability seems to be a rite of passage on the path to programming maturity. I certainly went through it. I remember laughing uproariously at some of P.J. Plauger's (very tight and regular) library code years ago. I even remember shouting something like "if a programmer working for me ever wrote code like that, I'd fire them!" I literally did not know what I was talking about.
评论 #5441419 未加载
daleharvey大约 12 年前
Often a good reason to use not so pretty code is for performance reasons, you didnt mention checking up on that so it would probably be prudent to do so (micro optimisations are totally valid for hot paths in libraries like jquery and browser performance is often very unintuitive)<p>Also if I was going to write it 'cleaner', I would find something like <a href="http://pastie.org/7118990" rel="nofollow">http://pastie.org/7118990</a> cleaner.<p>(but in essence I agree)
评论 #5440955 未加载