15 ms·
How to reduce the cognitive load of your code
- ryandev 11y agoWould recommend reading 'Code Complete' than this article
- HerpDerpLerp 11y agoHe does reference it in both the first and last paragraph! my fave is clean code... though uncle bob seems divisive these days for some reason. http://www.amazon.co.uk/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882 http://www.amazon.co.uk/Clean-Code-Handbook-Software-Craftsm...
- deleted 11y ago[deleted]
- davidhariri 11y agoNothing about division of concerns and organization?
- euske 11y agoIf I was to describe the essence of clean code in one word, I would say "balance". Yes, yes, readability and problem separation and stuff is important, but so is efficiency and usability and security and deadline and everything. Bottom line: balance. And it's the hardest thing to achieve.
- Klathmon 11y agoI've always worked through the idea that "Extremism is harmful". Literally anything taken too far is a bad thing. And just about everything in life is a matter of finding the right balance.
- diskcat 11y agoIsn't this just a fancy phrasing for "make your code easy to read"?
- hintingonwhoiam 11y ago+1 This whole blog post reeks of elitism and over confidence. The blog post over states its own importance as after learning these clean code would be easy. Like fade diets, magic paradigms etc... another example of someone believing or trying to convince others that there is a "magic path". "Just remember these four concepts", "get a six pack with just 20 minutes a day"... There are a few good tips in here but really nothing new. A nice reminder that there are some simple steps to help improve your own code. A large devil of clean code is not just in nitty gritty "have one line per logical action" but rather the deconstruction of a problem into easily followable steps. In that way this is definitely not an exhaustive description.
- deleted 11y ago[deleted]
- HerpDerpLerp 11y agoHe advocates prefixes on variable names. I would like to see good examples of this as I have never seen them as helpful (especially the tblUsers and intUserId type that can be common) .
- jordanlev 11y agoThis old chestnut from Joel should be helpful (or at least entertaining): http://www.joelonsoftware.com/articles/Wrong.html http://www.joelonsoftware.com/articles/Wrong.html He eventually gets to "hungarian notation" (those redundant prefixes you don't like) towards the end of the piece. tl;dr: misinterpretation of a good idea, cargo-culted down through the ages.
- jt2190 11y agoChristian 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 with the prefix "s" (for Safe string). us = Request("name") ...pages later... usName = us ...pages later... recordset("usName") = usName ...days later... sName = Encode(recordset("usName")) ...pages or even months later... Write sName The thing I want you to notice about the new convention is that now, if you make a mistake with an unsafe string, you can always see it on some single line of code, as long as the coding convention is adhered to: s = Request("name") is a priori wrong, because you see the result of Request being assigned to a variable whose name begins with s, which is against the rules. [1] http://www.joelonsoftware.com/articles/Wrong.html http://www.joelonsoftware.com/articles/Wrong.html (edit: formatting, citation)
- HerpDerpLerp 11y agoYeh I don't like abbreviations in code so would have unsafeName = Request("name") etc etc which does not have that problem... unless 'unsafe' is a thing in your business domain then things could get complex :) The article goes on to advocate prefixing the methods that return safe and unsafe strings with 's' or 'us' I would hate that! I can easily see you ending up with string methods like safePadLeft and unsafePadLeft that do exactly the same thing but are named for where in the code they are used... Coding is hard, and as other comments have stated all these blog posts and books need to be condensed into 'balance' and that balance point is different for each coder, project and team.
- jordanlev 11y ago> There are four main concepts I will talk about here. There are 5 concepts in the article. Off-by-one error? :)
- pjmorris 11y agoCognitive load is a harder problem than we give it credit.
- naringas 11y agoI used to think that a lot of bad code out there was made by lazy, incompetent programmers... But then, after a certain job, I realized that this is probably not the case. Now I belive that most bad code out thare is made by overworked and tired programmers in a rush to deliver something that works.
- phpnode 11y agoI think the reality is a mixture of both, the lazy, incompetent programmers are under pressure to ship too!
- reacweb 11y agoMost of the bad code was made by very productive developers.
- gahahaha 11y agoBecause productive developers write more code or because productive developers write worse code?
- mmebane 11y agoPerhaps being a "productive" programmer requires understanding the requirements well enough to quickly write working code, then moving on to the next problem. Personally, I usually find that it takes two refactorings/rewrites to go from initial working code to something that I honestly believe is understandable/maintainable, and I don't always have time to do that.
- mreiland 11y agoIt's more subtle than that. People act as if developers are all a clean slate, which isn't true. developers have personalities with differing values. That super productive developer may just not value the flexibility of the code due to his personality coupled with that developers personal experience. That developer will absolutely shine in some environments and be abysmal in others since there are absolutely environments where flexibility isn't an overriding concern. As you get more experience you learn to be more explicit about your decisions, but you'll still have your preferences and your defaults and it takes a certain threshold for you to move away from said preferences and defaults.
- couchand 11y agoThe article is well-intentioned but misses the point in a few places. For example, the suggestion to have, in an MVC project, three top-level directories: one each for models, views, and controllers. This works fine for small projects, but larger projects can see significant benefit by keeping related code together. As with everything, it's a judgment call. The simple "one folder per type of thing" rule may not be applicable in all situations.
- Can_Not 11y agoYeah, where do you add queues, events, observers, helpers, traits, interfaces, etc.?
- awinter-py 11y agoEach of those should be a separate module uploaded to NPM. That was the versions can vary independently (for max compatibility). This technique is named 'carbo-loading' (because of all the spaghetti).
- bdavisx 11y agoIt's been coined the LIFT Principle - aka "Folders-by-Feature" vs. "Folders-by-type". https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#application-structure-lift-principle https://github.com/johnpapa/angular-styleguide/blob/master/a... Unfortunately, since the simple examples use Folders-by-type, and many people are incapable (or unwilling?) to think for themselves - they just continue that way of doing things, even in giant projects. Hell, EmberJS embodies the Folders-by-type into the framework.
- raverbashing 11y agoVery good Until you have some code reviewer that thinks otherwise because of some "stupid reason" and you can't get around their hard heads. One example, breaking a 81 char line because it goes over the limit and getting two shorter lines that are awful to read So yeah I'll go for this when I'm working with reasonable people
- berntb 11y agoSo, what do you do if you get a job with Java or iOS and 30++ char method names? (Not being snarky, I would like to do some iOS development for fun but want lines under 78 chars, so it don't go over 80 with diff.)
- pivo 11y agoI do iOS development in Swift and I generally don't exceed 80 characters. It was much harder to stay under 80 with Objective-C but still usually possible. Everyone else on my team is in love with writing 120+ character lines, which makes me sad.
- kilink 11y agoSorry, it's just not practical to keep lines under 80 characters in some languages.
- igl 11y agoNo one ever mentions formatting. I really like aligning multiline blocks, adding whitespace and useless braces here an there. e.g: Having just a single space between function name and arguments makes it look less like a call. Yet almost all lint presets/defaults forbid this. Typography is all about the whitespace between letters forming easily recognizable shapes.
- Moru 11y agoYes, very important. I love editors that does most of this from a button press. Makes others code easier to understand. Netbeans have lots of settings so you get the braces and spaces where you want them.
- seanmcdirmid 11y agoTypography is much more than that, of course, but with fixed width plain text, you don't have many options...so ascii art it is. I'm pondering a language that includes formatting abstractions so that you can prepare code for reading along with its functionality (sort of like literate programming, but still starting from code). I would love to see comments in a side bar, long monotonous calls organized into tables, proper spacing and even lines to delimit sections, and so on... But our current programming systems, we are still very much in the dark ages of code typography.
- carussell 11y ago> I would love to see comments in a side bar This is brilliant. A neat way to bootstrap getting this sort of thing implemented in most code editors would be to write a plugin that can do this for existing code and make it good enough to turn heads. It would extract documentation blocks to be presented as prose in a vertically split pane to the right and present the file itself with those blocks hidden—as if automatic folding were turned on. It could even apply some fairly simple heuristics to automatically link to other relevant comments. The goal should be an experience indistinguishable from an embedded iframe showing human-generated API docs from the Web. Another thing I'd like to kill is the file tree that you see in most VCS Web frontends that tell you the last commit message that touched the file/directory, rather than about the structure of the code. Netscape's old Bonsai tool tried to do something like this. (When Netscape open sourced Mozilla, they also opened up a lot of their internal tools. This is where Bugzilla came from, but there were others, too.) When you were looking at a directory listing, if the file contained what looked like a short description of its purpose in the comments near the top of the file, Bonsai would grab description and present alongside the file name. In my own projects today, I try to always include a file overview containing a short, single line description and then write a paragraph or two going into further detail, documenting the whys of the code, and generally explaining its overall role in the project/justifying its existence. I'm basically writing for a tool that doesn't exist but that I'd like to see get created and gain widespread acceptance.
- hbt 11y agoThere 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, unnecessary comments, variables declared out of context or too soon etc.) - keeping terminology consistent across the code (domain language) - not using double negatives e.g a = !notLocked - using automated systems to simplify expressions (e.g weird boolean conditions http://www.wolframalpha.com/input/?i=a+%26%26+b+||+c http://www.wolframalpha.com/input/?i=a+%26%26+b+||+c ) etc. Unlike English, it is less difficult to have a program reorganize your code to make it more readable based on a set of cognitive principles. But, beyond the readability and understanding of a function, we should also learn from other engineering fields. For example, system thinking helps tremendously in organizing code if the cost of refactoring code wasn't so risky in dynamic languages.
- wpietri 11y agoAnd I'd say that the most important similarity is that good code and good prose can't be written in vacuum. "Any fool can write code that a computer can understand. Good programmers write code that humans can understand." - Martin Fowler Anybody who has written a book knows the feeling of slowly going crazy because you lose touch with how readers will take it. People writing long works in English have a host of tricks to overcome this. First, they'll have editors. Generally, they have more than one. They'll have sample readers, often quite a number of them. And then they iterate, going over something repeatedly to make it more readable. Writers I know will spend 2-3x the time in the revision process than they did in writing the first draft. For me, the best way to get that same feedback is pair programming. I was recently looking back at a code base produced by a small team I was on a few years back; the 4 of us did it with pair programming and frequent pair rotation. It is a great code base, one I'm entirely proud of. Clear, readable, well factored, intellectually coherent, and with amazing unit testing coverage. I think that's because every line, every change had two pairs of eyes on it, which meant that we were constantly evaluating readability, constantly testing and reducing cognitive load.
- 11y ago
- awinter-py 11y agoThe variable name you choose when writing a function may not make any sense when reading it a month later, or to a third party. These rules are as useful as feng shui -- if you have a good design sense, you can produce good results with FS. The readability wins I've seen come from using common tools; I'm going to be much more productive on a codebase written in a library ecosystem I understand. More generally, a powerful standard library with consistent calling conventions can help a language be useful. It's not productive for me to spend 10 minutes reading a function only to realize 'oh, this human wrote their own string split'. Tests help too because they make clearer the dependent typing of a function's call signature; stuff like 'don't pass both of these variables' or 'a must always be > b' are never clear (and I've never used a design by contract langauge). Tests are sometimes better than documentation because you can sometimes get alerted if they're wrong. Most important rule for readable code: hire programmers who know how to read. Reading a large project is a skill and lses people can read than write code. Every project is going to have a quirk of its evolution that's hard to understand without a close reading. (Every large C project contains a buggy partial implementation of LISP). Hire programmers who can survive that.
- noxToken 11y agoI've found that diagrams help. Young developers (in my experience) tend to laugh at the thought of making UML diagrams. At the very least, a class diagram will tell what classes references what. Using some custom stereotypes can help give further meaning. Ideally, sequence diagrams (or a similar type) can help shed light on just how the project comes together. Explaining how a project works from a high level can leave unintended knowledge gaps. The great thing about these diagrams is that they can largely be automated with very few inaccuracies. Diagrams are definitely now a silver bullet. I have found that they can easy grow unwieldy when attempting to incorporate too much information into a single diagram. Much like separation of concerns or the single responsibility principle, I believe that diagrams work best when they're focusing on a single piece of major functionality.
- ionforce 11y agoWhat is a stereotype?
- noxToken 11y agoStereotypes are an extension of UML to include extra information about the class. This[1] is a class diagram (albeit, overly detailed) I created for a library that we used. Above the class names are stereotypes. I know which classes came directly from the library, which are service classes, etc. [1]: http://i67.tinypic.com/33xyaz4.png http://i67.tinypic.com/33xyaz4.png
- hyperhopper 11y agoEven the first example is a bit silly. Nobody is going to not understand that (null == foo) is the same as (foo == null).
- a3n 11y agoAgreed. I understand the desire to make the variable of interest more prominent, by putting it first, but that particular bug is well worth defending against.
- bnegreve 11y agoIt does increase the cognitive load for no particular reason. Which is what the author is trying to avoid.
- Freaky 11y agoIt's the difference between, say, length(foo) and foo.length() - any difference in cognitive load should be lost in the noise next to "this variable can be null". And given most languages in use today use = to mean assignment instead of equality, it's hardly "no reason".
- retbull 11y agoExcept if you do if(foo = null){} it won't compile in java which is exactly what you want to happen. So using it in java is just cognitive load and provides 0 benefits.
- lkbm 11y agoHabits are hard to break. Switching back and forth between habits leads to mistakes. There's a trade-off here. I'm not going to say one is definitely worth it vs. the other, but if we pretend the disadvantages of one option don't exist, we lose the ability to make appropriate judgements.
- retbull 11y ago
- boothead 11y agoBiggest thing for me: have a small number of fundamental, composable abstractions. Be able to reason about how their properties interact when you combine them. This is the main reason that Haskell is such a force multiplier for me. All the small minutia is well defined and it frees you to think about the big picture. Sure, it's a big learning curve, but so worth it :-)
- hinkley 11y agoI spend a lot of energy discussing this at work, and mostly that has been "continue talking while people look at you like you have two heads" It feels like maybe people are almost ready to listen now. I don't know how this relates to the number of libraries we use now, or the StackOverflow culture, but I have my suspicions that they are related. Maybe we should start talking about Library Fatigue...
- matthewtoast 11y agoCode 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 features in a cluttered codebase is like being asked to install plumbing in a hoarder's basement. Understanding a cluttered codebase is like reading an advanced math textbook by candlelight that was written with broken typewriters by a group of modernist poets. De-cluttering is the first thing you should do, and you should stick to it above all else. Before you add tooling, before you refactor, before you abstract and framework-ize, get rid of the clutter. That means format your code, and use a linter whose rules are based on widely adopted community conventions.
- skewart 11y ago> 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.
- emiliobumachar 11y agoWhat's a Linter?
- tekromancr 11y agoIt's a tool that finds things that aren't strictly errors in your code, but are likely to cause problems. see also: https://en.wikipedia.org/wiki/Lint_(software) https://en.wikipedia.org/wiki/Lint_(software) (this article refers to one particular (original?) lint tool, but there are numerous others for various other languages)
- lostcolony 11y ago'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, but then I also made a change that needed to be shared, and whoops, I broke everyone" and the like). Not to mention trying to work with code deployed onto boxes without an IDE. I've gotten to where "if I can't make sense of it and be productive in it with just vim, grep, and find, your code is too complex".
- zeveb 11y agoI agree completely and totally. A good programmer's text editor (e.g. vi or emacs) is far more general than an IDE, more easily extensible and rather more future-proof (folks will still be using emacs & vim in twenty years; will anyone be using Eclipse?). Requiring an IDE is, to my mind, a symptom of a far-too-complex environment which will lead to breakage.
- CuriouslyC 11y agoPeople have been using eclipse for almost 15 years, and if they stop using it, it will be because there is a better IDE (see: IntelliJ). Things like smart auto-complete, click-to-definition, history/diff merge views and integrated build support/dependency management are a huge productivity win.
- ktRolster 11y agoThat reminds me when I first came across autocomplete, I thought, "Wow, this is really nice, I like it." Shortly thereafter, I had a horrifying worry that someday I would come across projects that couldn't be understood without autocomplete. And soon enough, my next job the code was impossible to understand without autocomplete and a debugger. I am still sad about that to this day.
- msluyter 11y agoWell, 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 after import into the IDE without any additional tweaks. I think it's sort of odd that many folks complain about IDEs, but then use vim with a million plugins. Isn't vim + plugins = IDE? Or, if the overall point is "java sucks, don't use java" then fine, but if you have to use it, I couldn't even imagine using plain old vim without any language support...
- norswap 11y agoLike 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 though). The real challenges are architectural: understanding how an application is structured is often a daunting task, and yet there are some very simple things one can do to combat this, starting with grouping things thoughtfully, generous pointers in the documentation, and a few paragraphs of architecture overview in the readme file.
- njharman 11y agoyeah, I'm not even sure what's suppose to be confusing? That the "constant" comes first, before the comparison operator?
- mikekchar 11y agoI think he's complaining that it doesn't read like English. You aren't testing null, you are testing the variable. There is an implication that the subject of the "sentence" will come first. Of course English order is idiomatic in most programming languages, but I don't think that means you can't have other idioms if there is a reason. I find it amusing that he complains about abusing fluent interfaces (making it read like English for no real benefit), but doesn't realize that he's doing the same thing here. That's why you have coding standards on your team. People agree on the idioms they use. Some people need to be told that it isn't an idiom if only one person likes it, though ;-)
- mc808 11y agoYoda speak, it is confusing like. Most people think "if the variable is not null" rather than "if null, the variable is not". It's easy enough to adapt to the style if it's used consistently throughout a code base, but that effort yields no benefits in most languages.
- 11y ago
- JoeAltmaier 11y agoIts not about understanding a line of code - anybody can do that. Its about absorbing kilo-lines of code and gaining an understanding of the whole thing. Without having to draw attention to every line. I can read code by the page, hitting next page at about a 1Hz rate. If the code is not overheated. That means, avoid lots of syntactic bloat, keep it concise, keep it modular, with low branching. Just about what the OP says.
- jimbokun 11y ago"Avoid using language extensions and libraries that do not play well with your IDE. The impact they will have on your productivity will far outweigh the small benefit of easier configuration or saving a few keystrokes with more terse syntax." This is the main reason to avoid Spring. Having so much critical code in XML and properties configuration files, annotations, and magical interfaces that somehow sprout implementations with no source code, make it impossible to debug using the normal techniques of Java development. "Show me all of the implementations of this interface method" "Show me where this object is instantiated" "Show me the code being invoked when I call this method" In my day to day work, Spring's only purpose often seems to be hiding the code that will actually execute when my program runs.
- msluyter 11y agoInteresting. Are you familiar with IntelliJ? My experience has been that its Spring integration provides most of what you're asking for.
- jimbokun 11y agoIntelliJ is amazing, and the only way I can function at all with our code base. But there are definitely still times when Spring manages to elude even IntelliJ. How anyone thought "magically appearing interface implementations with no code" was a good idea still baffles me.
- lr4444lr 11y agoIntellij IDEA is remarkably Spring-aware if you set it up properly. Static checks across schema-specified XML and Java is tight. That said, I couldn't imagine working with Spring if I weren't using IDEA.
- JustSomeNobody 11y agoBecause it is much better to let misspellings get caught during run time than compile time. /s Same with a lot of the DI frameworks that were so popular for a while. New guy doesn't wire something up correctly, checks it in and everyone spends the next 3 hours debugging a rabbit hole. (OK, slight exaggeration.)
- zwieback 11y agoSome good tips in this article but for me the problems usually start when I have to tie two or three APIs with different coding conventions together.
- freekh 11y agoNot sure I can say I always write clean code but when I do, in non-trivial cases, I often start to write a comment, delete it and replace the code I wrote with something that does not need a comment... I suppose it only works for people who (think they) know(s) what good code looks like, but (I think) it works as a good guiding principle (for me).
- kungtotte 11y agoThis is one of my guiding principles too. If I find myself wanting to comment the code to make it clearer or understandable, I refactor the code. The one time I let comments slide is when they document unexpected and unavoidable behavior that I can't fix in code. For example working with an inconsistent data set and having to add some convoluted code because what is a string in 95% of the rows might parse as a tuple in the remaining lines, so I need to account for that. This is so that I, or the next guy, knows why the code was written as such and won't go off trying to fix it.
- pklausler 11y agoI 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.
- macintux 11y agoYes, 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.
- enraged_camel 11y agoIn other words, a pure function. https://en.wikipedia.org/wiki/Pure_function https://en.wikipedia.org/wiki/Pure_function
- pklausler 11y agoIn mathematical words, a function.
- Kiro 11y agoWhat languages are you referring to? What languages do not support referential transparency?
- Yhippa 11y agoOne thing I appreciate about .NET are the conventions around project structure. When digging into an ASP.NET project I know where I can reliably find assets, models, views, and controllers. Also like conventions like prefixing interfaces with "I". Little things but makes diving into random codebases easier as a Java developer.
- iamleppert 11y agoDeveloper 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.
- tremguy 11y ago+1 for avoiding frameworks and extensions that don't play along with the IDE. I've only recently realized just how much the supposed productivity gains of those tools evaporate when your workflow gets bogged down.
- jimjimjim 11y agoone programming style that i think makes things worse is the "how many calls can i make on a single line" programming style. MyObjecter.GetObjectRelatativeThingy(ThingyHolder.WhatsMything(IndexKeeper.Get(), OtherWhatsIt.BuildOther( MoonCheese.Intensify(true))) It's probably a result of the letterbox effect of widescreen monitors and IDEs with horizontal toolbars and status bars. Is there anything wrong with expanding the idea of 'one purpose per function' into 'one purpose per line' and split it all up into multiple lines with temp vars inbetween. this gives you benefits of: - short lines and simple ideas - easier to set break points - allows for adding logging between calls. - allows for setting debug watches on the temp vars - the compiler tidies any temp vars away so there shouldn't be any extra copying.
- kungtotte 11y agoI like Raymond Hettinger's idea of one concept per line. Sometimes that means having two or even three functions on a single line, sometimes one.
- sklogic 11y agoThe best way to minimise the cognitive load is to always use DSLs.
- heisenbit 11y agoEspecially if there are objects that correspond to something real.
- bcheung 11y agoI've thought about this quite a bit from a language design standpoint. I've come to realize the following: 1) Reduce the number of variables that need to be kept track of in order to make a function easier to understand. 2) Avoid metaprogramming unless there is a clear need for it (doing something over and over). 3) DRY isn't always good. Sometimes being more verbose is easier to read than being clever so you don't have to type as much. Concentrate on readability first. 4) When there are a lot of interacting components consider the DCI pattern. It will save the developer from bouncing from file to file, module to module, just to understand the flow of an algorithm. Each time a developer needs to look up a different file more cognitive load is introduced. An algorithm should be easy to follow in a single file with code in sequential order. The opposite of this is message passing and having components pass messages to other components. 5) Syntax matters. Unfortunately once you choose your stack there isn't much you can do about this. Some syntaxes are much noisier than others. Every little bit of noise adds more cognitive load. Don't believe me, try do long division with Roman numerals. 6) Compress complex concepts into shorter ones. This builds on the Sapir-Whorf hypothesis. This might be a moving a part of an algorithm into its own function or storing an intermediate state in its own variable (as opposed to function composition 4 levels deep). `map` is much simpler to understand than `for (var i=0; i<arr.length; i++) { doSomethingWith(arr[i]) }`. 7) Spend time getting to know your editor. When you can reduce the amount of muscle movement required to perform an action it generally reduces the cognitive load as well. Not to mention making you more productive.
- fnordsensei 11y agoGood advice, but it still seems like just cosmetics compared to the real brainkiller: (incidental) complexity. It's kind of how legible handwriting is desirable, but not really the most important factor, when it comes to the amount of brain required to solve a math problem.
- jernfrost 11y agoOne thing I like which nobody ever seems to mention, is that when you divide your code into smaller functions it helps to have your functions actually take inputs and give outputs. It is very hard to read code which is just line after line of functions taking no arguments and returning nothing. No matter how descriptive your method names are, it will just end up being more confusing than if you simply wrote out all the code contained in those functions instead. People need to see how the code flows and how things are logically connected. That is impossible to do with reams of methods operating exclusively on member variables. I guess this is just another way of stating the benefits of functional programming. People do modularization at the function/method level so badly so often that I often think talking about modularization at class level, is beginning at the wrong end. So many struggle with modularization at small scale.
- erikpukinskis 11y agoHonestly, while I love these articles as food for thought, they really aren't the solution to the problem. In my experience, programmers generally have a sense of what parts of their code need to be cleaned up. If they are a newer developer their ideas might be a little screwy. They might not see the root problems, but they know which closets are producing ghouls. The issue I see is that developers don't think refactoring is a good a use of their time, or someone up the food chain doesn't think it's a good use of their time, or there's just so much institutional inertia making people question whether it's a good use of their time. If you want your code to be better though, don't read about architectural problems, just take some time to fix the stuff you know is bad in whatever way you know how. That's better than any article or class and it pays you money and it makes your code more fun.
- poofyleek 11y agoIs there a program that rates other programs in terms of Flesch Kincaid score or the equivalent? Old Man and the Sea F-K score is 4. Code isn't much different than other writings. I prefer to read code written like a Hemingway.