Live data from Hacker News

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

chrismm.com

151–160 of 187 posts

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

#151
post #121

This (arguably nice) post covers a small number of the points made in the book The Art of Readable Code: Simple and Practical Techniques for Writing Better Code [1] 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. I…

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

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

#152

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't really need my advice. These articles are addictive but I suspect reading Code Complete one page a day might be more useful and ultimately more enjoyable.

Why stop at 1 page a day? Code complete is an easy read that deserves to be enjoyed multiple times.

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

#153
post #60

Code Complete is an old book now. Is it still good advice? In my new project I see a lot of code like below. I hate it but I'm not sure if I'm old fashioned or correct in thinking it should be 4 or five lines. Should I reject a code review for stuff like this? return (HadoopSummary)ScopeCoordinator.getInstance().findObject(Scope.getFirst(), new Path (SCOPE_PATH.split("\\.")));

Not counting the fact that the book is old, i would generally not recommend it. The contents and topics have not changed that much but the book is just rather horrible to read. For whatever reason the author decided to ramble on for way to many pages instead of getting a point across in a concise manner. The whole thing should have been done in 300 pages instead of 900+. You will just start flipping pages without reading them and then put that gargantuan behemoth of endless words and sentences on the shelf (or return it to the library, delete the ebook or whatever).

That code does not look overly hideous (apart from the split magic string) just reformat it into a couple of lines.

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

#154
post #18

Sometimes I find myself writing in reviews for less experienced developers the comment: this is clever but not clear. 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/archaeologist in order to understand. What's funny is that often…

The counterargument:

http://www.linusakesson.net/programming/kernighans-lever/

It's worth looking at all the other pages on his site both before and after reading that article. Do you think he would've be able to accomplish all that if he "utilises only syntax and statements taught in an introductory programming course"?

What's funny is that often our future selves is the maintainer of our software.

IMHO if you find it difficult to understand code you wrote years ago, you have not actually improved. In fact, if this was any other skill (natural language, maths, etc.), the inability to do what you used to be able to, would be considered none other than a regression.

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

#155
post #89

Earlier quoted context omitted.

This 'reason' is as old as C, and it's always seemed to me like tying bells to your shoelaces because it would be bad if you forgot to tie them and tripped. I.e. the 'solution' is orthogonal to the problem. If you can train yourself to put the constant first, you can train yourself to use the right operator. And you can test your code.

> If you can train yourself to put the constant first, you can train yourself to use the right operator. Right... that's assuming you work solo. In that case, you might as well be using some higher level language and sidestep the whole issue. Most C programmers out there work in teams, in long lived projects... that means teams with rotation of personnel. This is a fuckup waiting to happen. I get you guys do not like…

The argument applies just as well to each member of a team.

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

#156
> 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.

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're accepting when hiring a junior.

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

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

#157

Earlier quoted context omitted.

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

Ruby version is a pretty clear one-liner: validated_items = items.select { |item| is_validated?(item) } Though I'd expect a check for validation to be an instance method, so it'd probably look like: validated_items = items.select(&:validated?)

Even if it's not an instance method you can write the first as

  validated_items = items.select(&method(:is_validated?))
(Typed on my phone but I'm pretty sure that's the right syntax)

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

#158

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

This is a rather idealistic approach to something which has real-world constraints: Despite our misinformed bathtub-curve view of the abilities of the software development community, the world is absolutely teeming with "average programmers", not superstars. It is in your best interests not to shut these folks out of your project if you want to guarantee that the people you hire are able to hit the ground running and not stop by your office every 10 minutes when they get stumped by some quirk in the codebase.

What you describe is the "Knotted Shoelace" antithesis to the ball of mud. Functional? Yes. Strong? Sure...but to re-lace your shoe you have to painstakingly pick it apart.

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

#159
post #76
post #29

Earlier quoted context omitted.

I love chaining, but one verb per line. Instead of something like Me.getFish.skin.debone.flour.salt.fry.eat It would be something like Me.getFish .skin .debone .flour .salt .fry .eat I find this more readable than doing it without chaining like this: fish = Me.getFish fish.skin fish.debone fish.flour fish.salt fish.fry Me.eat(fish)

I find the version without chaining easier to debug.

I don't know, I'd just set a breakpoint in my editor regardless of the form?

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

#160
post #122

Earlier quoted context omitted.

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…

>Do you really believe our brains are all the same? One thing that all brains have in common is that they can learn. One thing that all feet have in common is that they can not learn. That's why your analogy doesn't work here. >Functional programming is inscrutable by most. As is musical notation, maths, foreign languages, CAD drawings and everything else that has to be learned before use. I am not a huge proponent o…

> But one thing I am convinced of is that whatever newbies may find inscrutable is entirely irrelevant unless you plan to cut costs by having interns write all your code for free before replacing them.

I completely agree. My standard in choosing a design or syntax is whether a reasonably competent (but not brilliant) programmer will understand this well if they are already generally familiar with the codebase (but unfamiliar with this particular module) and are in a particularly big hurry.

As a specific example, I was horrified the first time I saw Java's convention for setting fields in a constructor:

  public class SomeClass {
      private final int shoeSize;
      private final String favoriteColor;
  
      public SomeClass(int shoeSize, String favoriteColor) {
          this.shoeSize = shoeSize;
          this.favoriteColor = favoriteColor;
      }
  }
The constructor has a local variable with the same name as the instance variable. The syntax works because local variables shadow instance variables but not when explicitly referenced via "this." -- a moderately obscure part of Java syntax.

Normally, I would object if a developer created a variable name that shadowed another and expected the reader to keep it straight and not get confused. But when you do this REGULARLY, it becomes just another standard idiom. Most readers today (now that the practice has been standard for over a decade) wouldn't even blink. A complete novice might be confused, but the complete novice isn't my target audience.

Post reply on HN