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

科技回声

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

GitHubTwitter

首页

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

资源链接

HackerNews API原版 HackerNewsNext.js

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

Writing good code: how to reduce the cognitive load of your code

317 点作者 SarasaNews大约 8 年前

25 条评论

agentultra大约 8 年前
Whenever I read articles like this and the ensuing discussion that follows, I&#x27;m reminded of this quote from Dijkstra:<p><i>Don&#x27;t blame me for the fact that competent programming, as I view it as an intellectual possibility, will be too difficult for &quot;the average programmer&quot; — you must not fall into the trap of rejecting a surgical technique because it is beyond the capabilities of the barber in his shop around the corner.</i><p><i>Dijkstra (1975) Comments at a Symposium</i><p>Whenever I read code written in the &quot;so boring it cannot fail&quot; camp I get exhausted. This code is inherently procedural and rolls itself into a giant ball of mud -- composition is difficult to achieve so as requirements change the code accrues more loops and conditionals until it is nearly incomprehensible.<p>It might start out neat and clean but rarely will it stay that way.<p>Good, non-leaky abstractions are key. This can even be achieved with procedural code but I think functional programming techniques like pure functions, immutable values, and a sound type system help a great deal... even at the expense of the initial &quot;cognitive load,&quot; it takes to learn how to employ these tools.
评论 #13817116 未加载
评论 #13815339 未加载
评论 #13818809 未加载
评论 #13819136 未加载
评论 #13819872 未加载
评论 #13820494 未加载
评论 #13819281 未加载
评论 #13821248 未加载
ser0大约 8 年前
Sometimes I find myself writing in reviews for less experienced developers the comment: this is clever but not clear.<p>I think as developers we get too enthralled in the problem solving and forget that in the long run we are more like journalists noting business rules at a snap-shot in time, which a future maintainer of our software must act as historian&#x2F;archaeologist in order to understand.<p>What&#x27;s funny is that often our future selves is the maintainer of our software. However, as we lament choices in the past, we continue to write intricate code in the name of elegance&#x2F;conciseness.<p>These days I&#x27;m pretty pleased when I can say a piece of code utilises only syntax and statements taught in an introductory programming course.
评论 #13819260 未加载
评论 #13814908 未加载
评论 #13814688 未加载
评论 #13814888 未加载
评论 #13814924 未加载
评论 #13819667 未加载
评论 #13818359 未加载
评论 #13818255 未加载
reikonomusha大约 8 年前
Some good previous discussion: Simple Ways of Reducing the Cognitive Load in Code <a href="https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=11992684" rel="nofollow">https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=11992684</a><p>My comment there is still relevant here:<p>I&#x27;ve noticed recently that especially in online discussions, the term &quot;cognitive load&quot; is used as a catch-all excuse to rag on code that someone doesn&#x27;t like. It appears to be a thought-terminating cliché.<p>There&#x27;s definitely room to talk about objective metrics for code simplicity, which are ultimately what many of these &quot;cognitive load&quot; arguments are about. But cognitive load seems to misrepresent the problem; I think it&#x27;s hard to prove&#x2F;justify&#x2F;qualify without some scientific evidence over a large population sample.<p>With that said, the article presented fine tips, but they seem to be stock software engineering tips for readable code.
评论 #13814576 未加载
评论 #13814570 未加载
评论 #13816218 未加载
评论 #13819098 未加载
awinter-py大约 8 年前
Hire programmers who can read.<p>Lines like &quot;Don’t use tools that are still too hard to get a grip on&quot; are code for &#x27;your team will get discouraged if they have to do any homework at all to understand your project&#x27;. If that&#x27;s true, how do you expect them to understand the business requirements?<p>Every large project has embedded tools and legacy tricks so the author is implicitly saying &#x27;don&#x27;t let projects scale&#x27;.<p>Simplicity is hard to achieve, and people who can&#x27;t understand complex code can&#x27;t write simple code.<p>If a book hits you on the head and makes a hollow sound, it may not be the fault of the book.
评论 #13824862 未加载
jacquesm大约 8 年前
It starts with picking the right language. Some languages help you to clarify your thoughts and some seem to do their best to obscure whatever meaning there was.<p>Then, after you&#x27;ve picked your language it&#x27;s up to you, the programmer. And &#x27;good code&#x27; to me translates into &#x27;whatever is on the screen is enough to understand the code&#x27;.<p>If you have to page back-and-forth all the time between different parts of a function or between different functions or even different files then your code will be hard to maintain, hard to read and probably buggy.<p>So work hard on reducing scope as much as you can.
mikulas_florek大约 8 年前
I expected some science, however it&#x27;s just subjective rules backed by nothing substantial.
评论 #13817954 未加载
pmarreck大约 8 年前
The largest improvement you can make to reduce the cognitive load of your code is to move to a functional language with immutable data and optionally static typing. Empirical data about bug tendencies by language <a href="http:&#x2F;&#x2F;macbeth.cs.ucdavis.edu&#x2F;lang_study.pdf" rel="nofollow">http:&#x2F;&#x2F;macbeth.cs.ucdavis.edu&#x2F;lang_study.pdf</a> is IMHO indirect evidence of cognitive load issues.
评论 #13818275 未加载
falsedan大约 8 年前
Writing good technical articles: if a part is probably the most important part, put it first (or nearly first) in the doc &amp; don&#x27;t waste the readers time congratulating them for spending 2 minutes reading.
mrlyc大约 8 年前
When I write code, I keep the target audience in mind. That target audience is a maintenance programmer doing their first programming job.
评论 #13817740 未加载
bipson大约 8 年前
This (arguably nice) post covers a small number of the points made in the book <i>The Art of Readable Code: Simple and Practical Techniques for Writing Better Code</i>[1]<p>I can recommend this to every programmer, even experienced ones, because even if they might know most of the things mentioned, it is presented in a very approachable, structured way and I think it always helpful, never boring and a diverting, easy read.<p>It also tackles these issues of &quot;Gurus say&quot; and &quot;Everybody knows...&quot; and tries hard to refrain from subjective matters, clearing up a few misunderstandings and old habits.<p>1: <a href="https:&#x2F;&#x2F;www.amazon.com&#x2F;Art-Readable-Code-Practical-Techniques&#x2F;dp&#x2F;0596802293" rel="nofollow">https:&#x2F;&#x2F;www.amazon.com&#x2F;Art-Readable-Code-Practical-Technique...</a>
评论 #13818863 未加载
11thEarlOfMar大约 8 年前
The highest compliment I ever heard, not paid to me, alas, was: &quot;Your code reads like a story!&quot;
stevecalifornia大约 8 年前
I like code that reads like a Dick &amp; Jane book (&quot;See Dick. See Jane. See Dick run. See Jane run.&quot;).<p>However, it appears to be trendy to write insanely difficult to read code. To use the analogy, Shakespearean code. Instead of one line of code doing one thing the developers will write a ton of functionality into one line of code by using fluent and method chaining. As someone reviewing the code I have to keep this mental stack of what the code is doing and it just becomes too much to process.<p>It&#x27;s a personal opinion, but I had to share.
评论 #13814794 未加载
评论 #13815742 未加载
评论 #13815044 未加载
评论 #13815107 未加载
评论 #13817904 未加载
评论 #13814581 未加载
sqldba大约 8 年前
&quot;Comments are closed&quot; says everything.<p>The if ($null -ne $blah) one is STILL RELEVANT. In PowerShell for example it differentiates between an empty array and either retrieving an array&#x27;s contents, or only the nulls from an array.
kccqzy大约 8 年前
I don&#x27;t understand the first example.<p><pre><code> if (null != variable) </code></pre> If this was C, it should be NULL, and it is almost always better to just write `if (variable)` to check for NULL pointers instead.<p>If this was JavaScript, this check includes undefined too. Not sure why it didn&#x27;t use triple equal.<p>If this was just talking about placing a constant value to be compared before a more complicated expression, I really don&#x27;t see a convincing argument for either. Does switching the order reduce the cognitive load that much?
评论 #13814967 未加载
评论 #13814470 未加载
评论 #13814557 未加载
评论 #13814430 未加载
评论 #13814335 未加载
评论 #13819082 未加载
评论 #13814521 未加载
评论 #13816430 未加载
评论 #13814481 未加载
rb808大约 8 年前
Code Complete is an old book now. Is it still good advice?<p>In my new project I see a lot of code like below. I hate it but I&#x27;m not sure if I&#x27;m old fashioned or correct in thinking it should be 4 or five lines. Should I reject a code review for stuff like this?<p>return (HadoopSummary)ScopeCoordinator.getInstance().findObject(Scope.getFirst(), new Path&lt;String&gt;(SCOPE_PATH.split(&quot;\\.&quot;)));
评论 #13817026 未加载
评论 #13819664 未加载
评论 #13818346 未加载
评论 #13816201 未加载
scandox大约 8 年前
Stone Soup: all you need to code well are just these few little pebbles of wisdom. Oh plus 15 years of learning how to apply them intelligently in any given situation, and subject to any given constraint. At which point you don&#x27;t really need my advice.<p>These articles are addictive but I suspect reading Code Complete one page a day might be more useful and ultimately more enjoyable.
评论 #13819642 未加载
Vinnl大约 8 年前
&gt; Libraries and tooling can also be a barrier for new developers. I recently built a project using EcmaScript 7 (babel), only to later realize that our junior dev was getting stuck trying to figure out what it all meant. Huge toll on the team’s productivity.<p>While I agree that libraries and tooling an be a barrier[1], I think getting junior devs up to speed with the (latest version of a) language is part of the toll you&#x27;re accepting when hiring a junior.<p>[1] Although this still holds true if you write the library yourself, so be reluctant in getting rid of libraries that save you more than they cost you.
hasbot大约 8 年前
The same holds true with APIs: too many concepts make a hard to understand API.
kuharich大约 8 年前
Previous discussion: <a href="https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=11992684" rel="nofollow">https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=11992684</a>
sirmoveon大约 8 年前
The day the cognitive load is at an ideal point is the day you will lose your relevance to society, because it will be easily automated. I know that day will come; but I&#x27;m in no hurry given the current state of affairs with capitalism and a global oligarchy trying to enslave the rest of the specie.<p>Meanwhile, I&#x27;ll be happy writing obscure and complicated code that I won&#x27;t have to maintain. Giving the industry leverage for the near future.
Jach大约 8 年前
At the risk of making too much over the section (and ranting risks in general :)) I get the sense that &quot;Keep your personal quirks out of it&quot; strays dangerously close to &quot;don&#x27;t learn anything new, don&#x27;t encourage the team to do it either&quot;. Of course I agree with not being clever for the sake of clverness, and not going against the overall style of the team with your preferred style. But the article goes on:<p>&quot;The problem is that people just want to fix their bugs and move on.&quot; Yeah, screw that, maybe if people spent some time learning better coding techniques they wouldn&#x27;t have so many bugs? Take for instance this &quot;trick&quot;:<p><pre><code> String blah = Optional.ofNullable(foo.bar()).map(Clz::doZap).map(OtherClz::extractZorp).map(OtherOtherClz::toString).orElse(&quot;&quot;); </code></pre> The normal &quot;just leave me alone and let me code and fix bugs and get on with life&quot; equivalent is:<p><pre><code> String blah = foo.bar().doZap().extractZorp().toString(); </code></pre> Problem: any of those method calls can blow up with NPE, because they were written long ago by other not so careful devs and you can&#x27;t simply rewrite. I see this all the time. Or a variant where foo.bar() is null-checked so they can call doZap(), but they still do (or edit it to do later) the rest of the chaining of doZap().extractZorp().toString(). When something inevitably does blow up, you get your bug to fix and then move on, but wouldn&#x27;t it have been better to not have the bug in the first place?<p>It&#x27;s not even that devs don&#x27;t realize that code could blow up with a NPE, a lot of the time they do, they just don&#x27;t want to do the ugly &quot;solution&quot; up front (that someone will end up doing when they fix the bug and move on anyway) of all the intermediary variables and if scopes checking for nulls (or a NPE exception handler in the middle of their logic) and convince themselves it probably won&#x27;t ever be null. The Optional &#x27;trick&#x27; lets them be lazy (low syntax overhead once you understand what map() and flatMap() can do) and safe.<p>Without even bringing up streams and lambdas, a nifty trick that appeared in Java not that long ago is the for-each syntax (which prevents all too easy to happen off-by-one errors in a loop counter). I keep up with language developments, I&#x27;m going to use new expressive capabilities in my code (when they&#x27;re helpful -- again I&#x27;m on board against cleverness-for-cleverness&#x27;-sake) and anyone who has a cognitive load with it ought to learn it well enough so there is no load and we can develop more solid code. Ultimately I concede the point I&#x27;ve heard from Haskell or Scala advocates that as you practice all that Type power becomes less troublesome, I&#x27;m just not willing to invest the cognitive effort up front to get to that point since I think the tradeoffs aren&#x27;t worth it for my use cases. The fact that I find a lot of Scala to be incomprehensible is a fact about my state of mind, not a fact about Scala or the developer who wrote the code.<p>In the end these aren&#x27;t even huge issues. The worst bugs aren&#x27;t often the result of presence&#x2F;absence of good code or capabilities (security bugs are probably a big exception), they often happen before coding even begins and accumulate over time with more and more edits to a system without stepping back to see if the original design makes sense for the current system or whether we&#x27;ve been stapling things together. We focus too much on these small details about how it takes 30 extra seconds to parse a too-terse line of code that would have been easier to swallow if it was 5 lines and ignore the fact that we&#x27;ve got 30 classes for this feature (so modular and testable) that could have been done in maybe 30 terse lines of a more powerful language with perhaps some extra cognitive overhead upfront.
评论 #13818324 未加载
mywittyname大约 8 年前
&gt; Actual code from a makefile I wrote. Junior devs can’t handle overuse of new tech.<p>Most devs can&#x27;t handle overuse of new tech. It seems like the <i>junior</i> qualifier was put into place in order to get away with this bit of hypocrisy.<p>The introduction of new tools will absolutely lead to increased cognitive load until the entire team is familiar with it.
tln大约 8 年前
I always feel guilty when using idiosyncratic code. A couple of jobs ago I briefly used this questionable Python idiom:<p><pre><code> var = &quot;%s code %s are bad&quot; var %= &quot;Stupid&quot;, &quot;tricks&quot;</code></pre>
JelteF大约 8 年前
Can this title be edited to say (2016)?
brilliantcode大约 8 年前
holy hell that interactive video&#x2F;code editor is pure fucking genius!!!!!<p>Is the mouse cursor an actual HTML element moving according to pre-recorded session?<p>Really would like some more details on this. I&#x27;ve never seen anything like it.