Live data from Hacker News

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

chrismm.com

161–170 of 187 posts

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

#161

Earlier quoted context omitted.

"If you don't have time to get it right the first time, how on earth will you have time to do it again?" I like that quote, but to be honeste. Some times you have to get it out of the door, and time is of the essence. And you can go back and fix it. That is okay, as long as you understand that shortcutting now, will cost time tomorrow (i.e. technical debt).

Yeah, the problem appears if your superiors don't understand that. It'll be a "quick fix", when you want to clean it up after the crunch the comments will be "nah, we don't have time for that right now" (non-coders never seem to understand that messy code is a liability - thus cleaning up code seems like a waste of time). And a couple of months later, it comes back biting you in the behinds. At which point, someone w…

> non-coders never seem to understand that messy code is a liability

If J. Random Folk were to go to the nearby mechanic to try and fix his car, he'd be very upset at him for stitching things with duct tape and calling it a day. Yet this is mostly the default expectation from "non-coders", who are all up in arms because you're being a "perfectionist" when you're just being a responsible professional. Sad.

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

#162
post #137

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…

> 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-identif…

There's nothing to be sorry about, actually, I'm really happy to learn that such research is being done! I tried searching for similar studies quite a few years back and came back empty-handed, so I assumed it's either not done at all or is very niche.

As you seem to be knowledgeable about the field, how relevant/applicable you think the studies you linked to are in the general case? In the study about identifier length, for example, seems to be very specific and I'm not convinced at all the results would be the same in a different language, with different people and even with slightly different identifiers (abbreviating start to str vs. beginning to beg, for example).

EDIT: another thought on the study: does it control for presence or absence of widely known conventions? For example in Haskell, OCaml and others it's customary to write `x :: xs` - would writing `element :: list` instead improve the time needed to comprehend the code? On the other hand, in Smalltalk, you frequently write `add: aNumber to: aList` - the identifiers are longer, but they provide additional (type) information which is otherwise not present. So how long the identifiers need to be may depend heavily on the language (the study used C# I think), is it accounted for in the paper?

Still, all the papers you mentioned look interesting and I will read them once I have some time. Thanks for posting! :)

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

#163

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 http://macbeth.cs.ucdavis.edu/lang_study.pdf is IMHO indirect evidence of cognitive load issues.

I'm a big fan of immutable objects. Best of both worlds in my opinion.

Well, there's somewhat of an argument to be made that immutable data structures are a bit less performant than mutable ones... but it still seems to be the way forward, especially when you take any sort of concurrency into account

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

#164

Earlier quoted context omitted.

IMO, all the points comes from 2 basic rules: 1 KISS (keep it simple and stupid) 2 DRY (don't repeat yourself) KISS being higher priority than DRY.

DRY isn't something you should blanket apply. There are cases where you do want to repeat yourself, e.g. to improve readability (avoiding metaprogramming, which is hard to reason about and will break your IDE) or because two things aren't actually semantically related (trying to force an abstraction means you need to undo it later anyways when the implementations diverge).

Yes, that is my point in giving higher priority to KISS.

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

#165
post #43

Earlier quoted context omitted.

Good point. I've been writing a lot of coffeescript recently, and the `is` operator insulates me from that whole situation. re [1] - javascript isn't the only language == isn't bad and wrong everywhere!

Ok, this explains a lot. What you are seeing is people taking specific C codying styles into other languages. This is a cargo-cult style and probably in detriment of your code base. On the other hand, it makes perfect sense in a C code base. The purpose of this is to transform a semantic error into a syntactic error. In C, both this expressions are legal but semantics is different: if (A == B) //Compare B to A, decid…

Putting constants before variables in comparisons is relevant in Javascript for the same reasons that it is in C. Perhaps even more so, since the browser compiling the code won't have -Wparentheses to lean on

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

#166

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.…

Imperative code can be clean and stay clean too, it just requires more effort. Remember that functional programs are easier to understand only because they are less expressive - they can't express concurrency and nondeterminism.

That being said, the principle of least power applies in full force, so if (a part of) your program can be written purely functionally, it should probably be written that way.

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

#167
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 is inscrutable by most.

I really don't think this is the case. FP is difficult for most developers who have experience with the OO/imperative paradigm - i.e., "most of us" - at first. It only takes about a week before the benefits become apparent.

Don't get me wrong, I don't think it's the solution to every problem, but spending a couple of months writing Clojure was a major positive experience for me, and it's significantly improved my day-to-day code in Python, Ruby, and Javascript.

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

#168
post #27
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…

I'm the accidental maintainer/guardian/dungeon keeper of a bunch of scary code at work, which happily does: if (false != aBooleanVariable) I still can't parse that without stopping and thinking (and sometimes cursing the original author). To me, with booleans , this can only sanely be written: if (aBooleanVariable) Code with literals is often worse than functionally equivalent code without; literals are complexity. A…

The downside in a dynamically typed language is that

if (aBooleanVariable) will return true for any truthy value, not just 'True'.

Of course I still prefer writing my if statements that way, it's just something you have to watch for if something does go wrong.

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

#169
post #73

Earlier quoted context omitted.

I would argue that by using CONSTANT == variable, you are reducing the cognitive load of the compiler, but increasing the cognitive load of the human reading the code (who has to mentally flip the expression around). I think the original article intended to say the same thing.

I don't get it. A test for (in)equality is commutative unless you're inducing side effects (i++) - and then side effects are going to be the big "cognitive load", regardless of which side of the comparison they occur. Am I dyslexic because (null != foo) is exactly as easy for me to read as (foo != null)?

At least in C++ you shouldn't count on the order in which a and b are calculated in a == b, because comparisons are not sequence points.

So no, even including side effects testing for (in)equality is commutative.

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

#170

Earlier quoted context omitted.

You'll also find that some experienced programmers specifically turn 1 line into 5. It's the beginner that tries to create the 1 liner because they think it's genius.

One-liners are bad if they are obscure and experienced programmers know that. However I wouldn't go as far as say that experienced programmers don't use one-liners at all. As usual in programming, it's all about balancing clarity/conciseness. For example, I find this much clearer as a one-liner (Python): validated_items = filter(is_validated, items) rather than validated_items = [] for item in items: if is_validated(…

"filter" has to be the worst library name. I have no clue what it's doing unless I read the documentation. On the other hand "append" feels like a much more conventional and comprehensible name.
Post reply on HN