Live data from Hacker News

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

chrismm.com

131–140 of 187 posts

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

#131
post #2

I don't understand the first example. if (null != variable) 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. If this was JavaScript, this check includes undefined too. Not sure why it didn't use triple equal. If this was just talking about placing a constant value to be compared before a more complicated expression, I really don't see a…

It's a poor example when testing for truthiness because it can be written more concise.

Imagine you're checking if the value is equal to a number or string. Placing the variable on the RHS avoids accidentally assigning a value to it if you mistype the comparison operator.

This is called Yoda conditions: https://en.m.wikipedia.org/wiki/Yoda_conditions

Edit: Many people already commented the same thing. Sorry for the noise!

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

#132

Some good previous discussion: Simple Ways of Reducing the Cognitive Load in Code https://news.ycombinator.com/item?id=11992684 My comment there is still relevant here: I've noticed recently that especially in online discussions, the term "cognitive load" is used as a catch-all excuse to rag on code that someone doesn't like. It appears to be a thought-terminating cliché. There's definitely room to talk about objecti…

> I think it's hard to prove/justify/qualify without some scientific evidence over a large population sample.

I agree with you, which is why I decided to gather some evidence about stuff like this. Here is a start - I have posted links to it before. Grab the preprint it will soon be ieee published:

https://brains-on-code.github.io/ (I am the first author of this piece).

Cognitive load in general is vague and hard to measure and thus difficult to find evidence for. However the effect of memory during program comprehension can be measured, as memory is well understood (tons of psych studies).

While memory surely plays a role to explain differences in program comprehension, it isn't enough to explain all differences. Experts in many experiments are often not impacted by bad code as much as novices, so experience also appears to play a role.

Memory is often said to be limited by its capacity, but most people ignore that the classic memory model explains linguistic encoding (e.g. there is not only long and short-term memory, but also a phonetic loop, an episodic buffer and a "visual/spacial clipboard"). This it is likely that code is influenced by language processing (thus, as my studie argues, one should use natural language words as identifier names), influenced by expectations (for example layout, style), etc.

But still that's not all. Some problems are difficult to decide. Imagine a short recursive algorithm for some problem, used appropriately. It might be an elegant solution, and could maybe replaced with a loop.

Does the fact that the solution is recursive, and thus builds a virtual tree, and maybe has a non-linear behavioral order, reduce cognitive load, or increase it? Should it be replaced with an equivalent loop?

What if we found out that the curly braces cause more cognitive load, when placed at the end of a function's signature, rather than on the next line?

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

#133
post #31

Earlier quoted context omitted.

I hear you. I don't like method chaining either. Instead of window.FindCanvasForObject(obj).Color(RED).MoveTo(10,30).LineTo(50,20). ... I much prefer: o = window.FindCanvasForObject(obj) o.Color(RED); o.MoveTo(10,30); o.LineTo(50,20); (Where, in C++ I would enclose this inside a { curly block } to give o the right type and make it local, and in Python I would add a "del o" at the end; and yes, I reuse 'o' to mean 'ob…

How about: window .FindCanvasForObject(obj) .Color(RED) .MoveTo(10, 30) .LineTo(50, 20) This avoids the repetition of the local variable name, while still making it clear what's being called on the object.

That particular chain breaks a rule that I find very helpful: when you see a vertical column of leading dots, those methods should all be acting on the same object. When you introduce a child object, indent another level.

So I would format that like this:

   window
     .FindCanvasForObject(obj)
       .Color(RED)
       .MoveTo(10, 30)
       .LineTo(50, 20)
Or more compactly:

   window.FindCanvasForObject(obj)
     .Color(RED)
     .MoveTo(10, 30)
     .LineTo(50, 20)

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

#134

Earlier quoted context omitted.

But on what object? The fact that calling .MoveTo(10, 30) would return the same object it has been called on, and not, for example, a handle to created movement animation, is not exactly obvious. Modern pattern of methods which just return the objects that they've been called on, by default seems to be very trendy, but I fail to see how is it helpful.

Er... on the window, as the indentation and API tells you. It may be "not exactly obvious" to you, but having been doing GUI programming for a long time, this makes complete sense to me. It is also, of course, a matter of personal style and preference. (Aside: some friends tell me, a vi user, that the way Emacs works is obvious. I disagree, but then, I don't use it). And as for "modern"... I've been using this since…

The indentation misled you here. The first method call returns a child canvas object that the other methods act on. See my comment nearby in this thread for an alternative way to indent that avoids this confusion.

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

#135
post #122

Whenever I read articles like this and the ensuing discussion that follows, I'm reminded of this quote from Dijkstra: Don't blame me for the fact that competent programming, as I view it as an intellectual possibility, will be too difficult for "the average programmer" — 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.…

Functional programming is inscrutable by most. Berkeley uses LISP as a flunk out class to weed out freshman. I find it odd that given in the physical world people require different shoe sizes for different feet that in the intellectual world people believe one size fits all, or that there is ultimately a single style of code that is comprehensible. Do you really believe our brains are all the same? The functional pro…

Functional programming has made huge inroads into mainstream languages over the last 20 years, so I suppose this is because people's brains have suddenly changed?

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

#136

Whenever I read articles like this and the ensuing discussion that follows, I'm reminded of this quote from Dijkstra: Don't blame me for the fact that competent programming, as I view it as an intellectual possibility, will be too difficult for "the average programmer" — 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.…

While I know Dijkstra's name only from a "historical perspective" (the algorithm, the goto-letter and some of his reasonings), I somehow grew very fond of a motivational-style picture of him almost frowning[1] with the title "quick and dirty".

I still would like to see a version that is of a high enough resolution so one could properly print, frame and hang it on an office wall. I like the idea that - when the next unavoidable proposal of "can't we just [...]" or "all we need is a prototype"[2] comes around - I'll be able to point to it and say something along the lines of "convince EWD first!".

[1]: http://www.catonmat.net/blog/difference-between-edsger-dijks...

[2]: Sometimes I wonder: Is there a "named law" for this? If not, why? It's never just a prototype.

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

#137

I expected some science, however it's just subjective rules backed by nothing substantial.

That's because no one even knows how to start doing "science" in this direction. When you read the code there are so many different things influencing your understanding that it's hard to impossible to even list them all. And if you take a look at some of the things that might influence your understanding you'll notice that most of them are very hard to impossible to measure. From the top of my head, things which may…

> That's because no one even knows how to start doing "science" in this direction

I am sorry to disagree, but this is just not true.

http://www.ptidej.net/courses/inf6306/fall10/slides/course8/...

http://www.cs.kent.edu/~jmaletic/papers/EMSE12.pdf

https://link.springer.com/journal/10664

https://scholar.google.com/citations?view_op=view_citation&h...

I have to say this:

https://brains-on-code.github.io/shorter-identifier-names.pd...

My supervisor has to say this:

http://pi.informatik.uni-siegen.de/stt/34_2/01_Fachgruppenbe...

These are just the ones from the top of my head that I can google quickly, if you want I would be happy to share my zotero database or a large bibtex file.

> When you read the code there are so many different things influencing your understanding that it's hard to impossible to even list them all.

You are completely right: Psychological research on programming shows that it is a very complex cognitive task, best done by experts, and poorly understood.

You describe knowledge and experience, and they in fact matter a lot. The above studies, for example, show (often just as a sideeffect), that experts are impacted less severely by badly written code (however that was operationalized).

> Literate Programming should be the default by now

I agree.

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

#138

Earlier quoted context omitted.

That's because no one even knows how to start doing "science" in this direction. When you read the code there are so many different things influencing your understanding that it's hard to impossible to even list them all. And if you take a look at some of the things that might influence your understanding you'll notice that most of them are very hard to impossible to measure. From the top of my head, things which may…

Science is hard, especially if done properly. The least they could do is to spit teams in two groups, based on whether they use a technique or not (e.g. unit testing, using OOP) and see if it makes any difference. It's far from perfect, but better than nothing. > That's because no one even knows how to start doing "science" in this direction. I suspect the reason almost no one do SW science is that nobody really care…

As my other comments outline, there is some science, although you are right in that empirical work on software engineering is a very small niche. Most people just report studies like:

"Hey, look what I cooked up in my basement using haskell".

- which to me, is engineering, not science.

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

#139

Earlier quoted context omitted.

Hmm -- you're talking about programming in the small, as in line-by-line style. Cognitive load also affects devs at the scale of a whole project, i.e. understanding how the program fits together across different modules, across state changes and across time. What's the dick & jane solution for project-scale organization?

Bingo. People like to hold forth on the small scale - but what about communication between components? I watched "The Art of Destroying Software" [1] the other day and I've been thinking about the concepts a lot. Thought provoking talk - apart from the surveys he keeps conducting. Making a nice method isn't that great. But a nice "component" or "module" or "service" - that's the key. Try and break your program up int…

The topic is good, but these short sentences and long pauses between the sentences make it really really hard to watch.

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

#140

Earlier quoted context omitted.

Er... on the window, as the indentation and API tells you. It may be "not exactly obvious" to you, but having been doing GUI programming for a long time, this makes complete sense to me. It is also, of course, a matter of personal style and preference. (Aside: some friends tell me, a vi user, that the way Emacs works is obvious. I disagree, but then, I don't use it). And as for "modern"... I've been using this since…

The indentation misled you here. The first method call returns a child canvas object that the other methods act on. See my comment nearby in this thread for an alternative way to indent that avoids this confusion.

I think it just proves my point. Do we really want indentation to be that critical to making code readable?
Post reply on HN