Live data from Hacker News

How to reduce the cognitive load of your code

chrismm.com

121–130 of 239 posts

Re: How to reduce the cognitive load of your code

#121

I didn't appreciate how much of a difference it would make until I tried it, but now I know that one of the best ways of making code more comprehensible is to eliminate any questions about interactions between components by using a language with referential transparency. The results of functions should be determined solely by the values of their arguments, with no contamination by shared state and no side effects.

Yes, yes, yes.

Refactoring code without side effects is so incredibly liberating: I barely have to compile many changes, much less carefully test them, because they're so obviously correct, because I can SEE the flow. I don't have to speculate on what the rest of the system thinks is going on.

Re: How to reduce the cognitive load of your code

#122
Developer cognitive load is one thing that kills projects, teams, and, eventually organizations. In the various companies and projects I've worked on, you can usually spot the culprit: a single person, or small group of people who take pride in making things more difficult for others to understand, or actively creating insider systems that serve to entrench themselves and make them seem important and the center of attention.

Re: How to reduce the cognitive load of your code

#123

Earlier quoted context omitted.

There is a tool for literate coffeescript that formats the output in a similar way - you have the english text in a pane on the left and the code in a pane on the right. I quite like the effect -- especially since there are potentially no comments in the code at all, which I often want if I'm just trying to read it quickly. Unfortunately, literate coffeescript is not really mature enough to be used in a large project…

It doesn't really sound like the same thing I'm talking about, to be honest. And I find the idea of a tool that automatically rewrites machine readable code into a natural language to be of dubious value beyond use cases where someone is first picking up the language. Similar to those tools that exist to generate comments in the form "Set global position" based on a method named setGlobalPosition. It just creates red…

I think you might be misunderstanding what "literate programming" is. It's a method of programming where you embed code inside English language documentation. The idea is to be able to present the documentation in a way that is useful to a human, but have the compiler extract the computer code and reassemble it in the way that the computer would like to see it.

Literate coffeescript does not have the tools for extracting and rearranging text, so it's really just a way of embedding markdown text into your coffeescript code. However, it's useful because you can embed html hyperlinks which can do things like enable you to click to get to the tests, etc.

Here is a small example of something I wrote in literate coffeescript: https://github.com/ygt-mikekchar/react-maybe-matchers/blob/m...

Now imagine that you have the English text on the left hand side and the source code on the right hand side. Ideally you would have tools that would allow you to make the hyperlinks (possibly automatically) and keep the documentation in sync. Such tools do not yet exist at the moment, unfortunately.

Edit: I should admit to being embarrassed about my fluent interface abuse in this code ;-)

Re: How to reduce the cognitive load of your code

#124

Earlier quoted context omitted.

I like to break lines and use indentation to line up repeated text, so you can see there is repetition, and so the parts that are different are obvious. A simple example: if ((mouse.x == 0) && (mouse.y == 0)) { scores more points than: if ((mouse.x == 0) && (mouse.y == 0)) {

maybe if(mouseIsAtOrigin()){

The point wasn't to come up with the best api, but to illustrate how to format code that has repetitions and regular variations in it, to make it easy to visually identify which parts repeat and which parts vary. That makes it easier to read the code and spot errors.

For example:

    sqrt((x * x) +
         (y * y) +
         (z * z));
You can run your eyes up and down each column to verify it's squaring x, y and z.

That reflects the structure and symmetry of the expression better than:

    sqrt((x * x) + (y * y) + (y * z));
Did you spot the error?

    sqrt((x * x) +
         (y * y) +
         (y * z));
How about now?

Here's some code that has a lot of examples of that style, a JavaScript implementation of a weird hybrid Margolis cellular automata neighborhood, which has a lot of two-dimensional patterns:

https://github.com/SimHacker/CAM6/blob/master/javascript/CAM...

Re: How to reduce the cognitive load of your code

#125
post #17

Earlier quoted context omitted.

Christian points to Joel Spolsky's example of using prefixes to add meaning, not type information like your examples. From Joel's essay: All strings that come from [user input] must be stored in variables (or database columns) with a name starting with the prefix "us" (for Unsafe String). All strings that have been HTML encoded or which came from a known-safe location must be stored in variables with a name starting…

In modern type systems (Haskell, etc.) you can define a new type that wraps an existing type with zero runtime cost. In Haskell you could write newtype UnsafeString = Unsafe String (UnsafeString is the name of the type. Unsafe is the constructor you use to create an UnsafeString from the String). With this and other techniques you can lift these characteristics of you data into the type system, which is IME much more…

I don't think the Haskell typing system is powerful enough for completely replacing prefix labels.

Marking something unsafe is a best case scenario. Separating lines from rows would require a huge amount of boiterplate to preserve the numeric operations, and one still can not create a library that will check something like:

    let
    l = 5 :: Meter
    w = 4 :: Newton
    in l * w :: Joule

Re: How to reduce the cognitive load of your code

#126
post #27

There are so many similarities between writing code and writing English. - Thinking of paragraphs as functions with one purpose - keeping sentences short to reduce load on working memory and increase comprehension - create visual breaks to help the reader by grouping common stuff together as mini-functions - reduce intimidation factor of reading by removing convoluted stuff - remove cognitive noise (dead code, unnece…

Based on your list of how you like to write English, I agree. But I think your list is way off-base when it comes to human languages. The beauty of human language is that it allows us to express our individuality as humans. There are an infinite number of ways to write the same thing, and each author can have a unique style based on how they choose their words, structure their sentences, etc. This is fantastic, and i…

Different guidelines for different writing. I will readily agree that this list would result in awful poetry, but then again, uniqueness and individuality would result in equally awful technical writing. So it's not that this list is off-base for human languages. Rather, it's off-base for art.

Re: How to reduce the cognitive load of your code

#127

Code clutter is much more consequential than it gets credit for. Poor formatting, inconsistent whitespace, snips of unused code, and misleading filenames are speedbumps (or worse, spike strips!) that a developer is going to hit every time they sit down to code. And unlike bad abstractions -- which you can "learn" about and mentally model -- the friction of clutter is a constant damping to your productivity. Building…

> Building features in a cluttered codebase is like being asked to install plumbing in a hoarder's basement.

Hah, yes! That's a great analogy. It doesn't mean you can't get the job done, it just slows you down every time you move around the code base.

Re: How to reduce the cognitive load of your code

#128

'Avoid using language extensions and libraries that do not play well with your IDE' I'm of the opinion this should be extended to "does not play well without an IDE". Because even in projects that said "everyone, use Eclipse(/IntelliJ/whatever)", and tried to share project files, there was constant pain in ensuring that everyone had the same development environment ("Oh, yeah, I made a local change to my project file…

Well, sure, but that's why you don't share project files. I think that if you do things correctly, your concern is mostly mitigated. My last job was Java/Spring. As someone noted above, you really don't want to be working with Java/Spring without IntelliJ. But we never had issues with anyone breaking builds due to screwing up project files, because those weren't shared and the project would run/build/test immediately…

Sure. Does it require a specific IDE then? Does it cleanly import, from scratch, with working tests and etc, regardless of whether they're using Eclipse, IntelliJ, Netbeans, etc? Or is there One True IDE? Is that IDE available everywhere you have to touch code? Is it straightforward to integrate it with your CI/CD tools, despite conforming to that IDE convention? Will it continue to cleanly import after you've left the code to rot for a couple of years in production, and then have to come back in to maintain it? Etc. I've been bitten by all of these.

Whereas I've gone to projects that were written without all of this, and even without getting the code to even compile locally (because of dependency hell that I didn't want to suffer through if I didn't have to), was able to diagnose and fix issues, because the code was written to be understood with only a text editor.

Re: How to reduce the cognitive load of your code

#129

'Avoid using language extensions and libraries that do not play well with your IDE' I'm of the opinion this should be extended to "does not play well without an IDE". Because even in projects that said "everyone, use Eclipse(/IntelliJ/whatever)", and tried to share project files, there was constant pain in ensuring that everyone had the same development environment ("Oh, yeah, I made a local change to my project file…

Someone wrote a post a while back about this topic and called it the grep test. See: http://jamie-wong.com/2013/07/12/grep-test/ It's funny that you mention the Java ecosystem as one of the worst offenders, since the nature of the language itself and the culture around best practices in the early days should have put it in a particularly favorable position here. This is covered partly in another great post titled "Ja…

Even more amusing, I didn't mention Java, just IDEs popular with Java (but which support other languages too). I was certainly thinking it, though. As were you, as soon as you read the description of the problem. Yay, validation.

Re: How to reduce the cognitive load of your code

#130
post #59

Like often with this kind of article it barely scratches the surface. "null != variable" will confuse people is downright silly. People confused by this won't have an inkling of what any non-hello-world program does. The rest has some validity, but it focuses on syntax and programming in the very small. It might take a bit of effort, but I can make sense of a tangled function (that's not an excuse to code sloppily th…

I think you're reading too much into 'confusing'. It won't leave someone without understanding; it -may- cause them to momentarily pause, going "WTF?...uh...probably does ~this~. But why would someone do things this way?" That's still delaying them, that's still distracting them, that's still putting up an obstacle. Not one a future maintainer can't overcome, but -why do it-? That's the point.
Post reply on HN