14 ms·
Writing good code: how to reduce the cognitive load of your code
- kccqzy 10y agoI 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 convincing argument for either. Does switching the order reduce the cognitive load that much?
- yannickt 10y ago"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." Imagine that it was this instead: if (5 != variable) As the author points out, this was typically used by C and C++ developers to prevent accidental assignments inside conditional statements.
- paxcoder 10y agoTo paraphrase the comment above that line, they say its purpose is to avoid accidental assignment. That's not an issue with "not equals" though, but that may just be their point. As for whether it's more readable, I'm skeptical: It may save you going through some of the condition, but I believe getting used to it would make you more likely to overlook parts of the condition. Plus, the way it reads is the opposite of how you'd say what it does in English. F̶i̶n̶a̶l̶l̶y̶,̶ ̶o̶b̶s̶c̶u̶r̶e̶ ̶a̶r̶c̶h̶i̶t̶e̶c̶t̶u̶r̶e̶s̶ ̶m̶a̶y̶ ̶d̶e̶f̶i̶n̶e̶ ̶a̶ ̶n̶o̶n̶-̶z̶e̶r̶o̶ ̶N̶U̶L̶L̶ (see to3m's reply). Using NULL makes it easier to find null pointer checks and conveys semantics (pointer vs integer).
- to3m 10y agoA NULL literal in c is always zero. The compiler generates code to produce the right address (which may not have all bits reset).
- gamegoblin 10y agoTo provide a different opinion, I'm not a fan of the macro NULL because the C spec leaves it rather open to compiler authors how to expand it. It says it must be 0, but they don't specify the type. It could be 0, 0L, (void*) 0, 0UL, 0LL, etc. However, the spec does say that only the null pointer evaluates to false and all other points are true. So doing if(ptr) is much more well-defined than the NULL macro.
- paxcoder 10y agoIf anything, NULL's opacity is another argument for doing the comparison. NULL is guaranteed not to equal any pointer to an object/function, and the result of the comparison will be an int 0 or 1.
- sdegutis 10y agoThe article says: // This was useful in C to avoid accidentally // typing variable = null. These days it will // confuse most people, with little benefit. The use of "was" and "these days" in the link shows that the author of this piece is in a tiny little bubble of development, and is far from being able to give general advice for programming. C is not past-tense. C, C++, Objective-C, these are all still widely used today by modern professionals. I'm very tired of articles and authors which claim to be representative of all programming or programmers, when they're isolated to a tiny little bubble. Especially when they only know JavaScript.
- haswell 10y agoHe follows this up with: > Don’t code “your way”. Just follow the coding standards. This stuff is already figured out. Make your code predictable and easy to read by coding the way people expect. I'm not a C dev, but is "(null != thing)" still a convention? (Based on your comment it sounds like yes). If yes, it seems to me like he's saying: keep doing that! Nowhere does he claim that his advice about this convention applies to every language (this would be silly) and not writing C should not preclude someone from giving programming advice. The "generally applicable" advice that he does give is exactly that: general. Is it possible to write a blog post about code quality/complexity/insert-thing-here that applies to all circumstances? I don't believe it is. It doesn't mean that there is no value to be gained from exploring concepts that may apply.
- MaulingMonkey 10y ago> I'm not a C dev, but is "(null != thing)" still a convention? Configuring the warning your compiler gives for 'if (x=y)' to generate an error instead is a vastly better convention that completely supersedes Yoda style, IMO. 'if ((x=y))' remains available for those who really want to assign in conditionals.
- Ace17 10y ago> I'm not a C dev, but is "(null != thing)" still a convention? (Based on your comment it sounds like yes) I'd rather call it a trend than a convention.
- falsedan 10y ago> almost always better to just write `if (variable)` Close enough works for horseshoes but not for C. It has to work 100% of the time to be acceptable (int variable = 0;)
- watwut 10y agoI haven't wrote in c for years and still don't get what is supposed to be confusing about it. Maybe he wanted to check for undefined too? Most often you want to treat it the same as null.
- flohofwoe 10y agoI also don't understand this, nothing wrong about Yoda conditions and I don't understand the 'cognitive load' argument since the condition is just as readable. And: Visual Studio 2015 does not warn in the case of "if (a = 5)", not even at the highest warning level, only the VS2015 static code analyser catches this.
- maccard 10y agoIt also probably shouldn't (warn) if(Foo* a = GetAFoo()) { /* Do something with a non-null foo */ } is perfectly valid code.
- gnaritas 10y agoDepends on the language, C# won't allow that, if's don't accept null, they accept bool.
- maccard 10y agoTrue. I was speaking of C++, which also accepts bool [0] (or more specifically, something that can be converted to a bool, which a null pointer can be [1]). Actually [0] has a good example of when the if (Foo* a = ...) syntax is useful (dynamic cast) [0] http://en.cppreference.com/w/cpp/language/if http://en.cppreference.com/w/cpp/language/if [1] https://ideone.com/im4uVn https://ideone.com/im4uVn
- kccqzy 10y agoI believe that's a declaration inside `if`. C doesn't support that, but C++ does. I believe in this case you can't actually put parenthesis around it.
- to3m 10y agoWith Visual Studio 2015 update 3, and /W4, I get "warning C4706: assignment within conditional expression" for stuff like "if(a=5)", both in C and C++. (C4706: https://msdn.microsoft.com/en-us/library/7hw7c1he.aspx https://msdn.microsoft.com/en-us/library/7hw7c1he.aspx)
- unwind 10y agoI'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. And I hate literal comparisons with true and false for booleans. Aargh.
- dozzie 10y agoI thought up at some point something like this: return (aBoolean != false) ? false : true; So ridiculous that it made me laugh.
- pythonaut_16 10y agoThe 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.
- joshvm 10y agoNowadays you should do it the readable way and let the compiler detect problems for you. If you use -Wall on any modern compiler, this will be caught. There are some weird use cases when you actually want assignment in the condition statement, but all those cases could be added with an extra line, e.g. the valid statement: if(Foo* someFoo = getFoo()){ could just be replaced with Foo* someFoo = getFoo(); if(someFoo){
- slavik81 10y agoThe former constrains the scope of someFoo to if statement, while the latter does not. Minimizing variable scope is one of the things I find really helps reduce cognitive load, so I'm not sure I'd want to make that replacement.
- reledi 10y agoIt'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 https://en.m.wikipedia.org/wiki/Yoda_conditions Edit: Many people already commented the same thing. Sorry for the noise!
- stevecalifornia 10y agoI like code that reads like a Dick & Jane book ("See Dick. See Jane. See Dick run. See Jane run."). However, it appears to be trendy to write insanely difficult to read code. To use the analogy, Shakespearean code. Instead of one line of code doing one thing the developers will write a ton of functionality into one line of code by using fluent and method chaining. As someone reviewing the code I have to keep this mental stack of what the code is doing and it just becomes too much to process. It's a personal opinion, but I had to share.
- adamnemecek 10y agoThis only a problem in dynamically typed languages.
- jmcomets 10y agoJust so this is clear, in Java this pattern is very present, especially since Java 8 (Streams). Before that, there was the Builder pattern[1]. It's also present in C++/C# in the same form. [1]: https://en.wikipedia.org/wiki/Builder_pattern https://en.wikipedia.org/wiki/Builder_pattern
- TimJYoung 10y agoI can't up-vote this enough. As someone that started doing development in the late 80's, I find this style of coding to be infuriating. It completely destroys the ability to map lines of code directly to function calls without resorting to manual coding rules that require that each .function() be on a separate line, and makes debugging way harder than it needs to be. And, for what purpose ? To avoid a local, temporary variable ? Do these developers think that their code is faster this way, or...what ? It's "write-only" code - good luck to the next guy that has to read it. And, don't get me started on: if <Constant> = <Variable>... :-)
- MrLeap 10y agoTo get you started, I'd like to compare my problems regarding `if <Constant> = <Variable>` with yours. This assumes you aren't the kind of lunatic to actually assign a constant inside of an if's condition. 1. I can't articulate exactly why, but that should totally be flipped. The constant should be on the right side! `if(3.17 == possiblyPi)` would make me seriously question the author's motives. 2. It's personal preference, but in almost every situation I'd prefer to use a switch over an enum than lots of constants.
- hasbot 10y agoThe same holds true with APIs: too many concepts make a hard to understand API.
- falsedan 10y agoWriting good technical articles: if a part is probably the most important part, put it first (or nearly first) in the doc & don't waste the readers time congratulating them for spending 2 minutes reading.
- reikonomusha 10y agoSome good previous discussion: Simple Ways of Reducing the Cognitive Load in Code https://news.ycombinator.com/item?id=11992684 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 objective metrics for code simplicity, which are ultimately what many of these "cognitive load" arguments are about. But cognitive load seems to misrepresent the problem; I think it's hard to prove/justify/qualify without some scientific evidence over a large population sample. With that said, the article presented fine tips, but they seem to be stock software engineering tips for readable code.
- afarrell 10y agoIt is hard to judge the cognitive cost to someone without knowing what that person's pre-existing mental models are. I don't quite see how cognitive load is a thought-terminating cliche though.
- gravity13 10y agoI think cognitive load is a perfectly acceptable term here. Taken within the context of Cognitive Load Theory, we assume that any individual can only maintain a few items into their working memory. These items are portions of the code that you need to think about at once in order to achieve a task, and good code partitions off the logic so that in order to understand individual components you only need to reserve a few slots of your working memory. Of course this is a bit contrived, but I would argue that pretty much everything we've come to understand as "easy to read code" all reduces down to how effectively it organizes itself given the limitations of our working memory. And in that case, it's one of the first things you should be sure to understand on your path to becoming a better programmer.
- dualogy 10y agoThough your points seem (technically) on-point, you might be missing the one facet of the "cognitive load" concept that I think is the defining one: as time marches on, entropy increases and in tech that means, cognitive load does. Every day there are new command-line tools and arguments and combinations and compositions, every week new languages, every quarter new syntax sugars in minor releases of major languages, every other year new major framework versions each with twice as many new libs/APIs as the previous release, etc etc .. even with Google and StackOverflow integrated into your hypercontextual IntelliSense etc IDE, it Just. Friggin. Grows. Out. Of. All. Control at least easily perceived so. Nevermind the constant stream of new NPM packages or fresh Haskeller-PhD papers. (And everything constantly sounds game-changing-as-heck too, funnily enough. Guess that happens when we all grow up around advertising ;) Dead-simple "ELI5" code alleviates many headaches here, simply by not piling even more layers on top of all those we can't afford to ditch in the real world, much as we'd love to. "Simple code" to "reduce cognitive load" was even an early helpful lesson for the id guys as shown a few days/weeks back: http://blog.felipe.rs/2017/02/25/id-software-programming-principles/ http://blog.felipe.rs/2017/02/25/id-software-programming-pri... --- and they had to deal with way fewer foreign/3rd-party baggage, writing Asm/C for DOS games that run just a tiny level above lowest. At some point we'll all switch to Brainfuck: at least, there's only 8 primitives to keep in your mind at all times ;) seriously Assembly language is becoming ever more appealing. With fewer abstractions, you get more LoC but at least you grasp exactly what's meant to happen. Higher-level intent not so much, regrettably, unless commented of course.
- brilliantcode 10y agoholy hell that interactive video/code editor is pure fucking genius!!!!! Is the mouse cursor an actual HTML element moving according to pre-recorded session? Really would like some more details on this. I've never seen anything like it.
- ser0 10y agoSometimes 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 our future selves is the maintainer of our software. However, as we lament choices in the past, we continue to write intricate code in the name of elegance/conciseness. These days I'm pretty pleased when I can say a piece of code utilises only syntax and statements taught in an introductory programming course.
- gravity13 10y agoEverything is unclear until you become used to it, though. I mean, used to it, as in, you can read it without stepping yourself through the steps manually. And to a novice programmer, pretty much everything they come up against represents this. Turning five lines into one line with a reduce function sounds like a normal thing to do for experienced programmers, but to a beginner, they'll think you're a genius for pointing it out to them. So it's not surprising when they try to apply their genius and come up with something clever, too.
- pugworthy 10y agoYou'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.
- jmcomets 10y agoOne-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(item): validated_items.append(item)
- mikulas_florek 10y agoI expected some science, however it's just subjective rules backed by nothing substantial.
- klibertp 10y agoThat'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 have an impact: * your level of skill in a given language * your level of familiarity with the style of a particular programmer who wrote the code * the tools you have at your disposal (go to definition, see docs functions of IDEs) * your familiarity with a particular framework used * your preference and expectations regarding the identifiers * your knowledge of what the system as a whole (or its part) is supposed to do * your familiarity with the project structure And so on, and that's even before we start talking about concrete examples of readable code and trying to get some metrics on it! Writing code is no more susceptible to scientific analysis than writing prose when it comes to other people reading the code (and not machines executing it). To write good code you need to first assume something about your readers (their level of skill, prior experiences, etc.) and then optimize the form of the code so that it doesn't confuse them (too short) or bore them (too long). Seriously, writing prose and code (the latter only if meant for human consumption) is very similar: you need structure, things following one another, sentences of appropriate length and "density" and so on in both kinds of writing. Programmers could learn a lot from writers, but they most often refuse to do so. Literate Programming should be the default by now, yet is still used very rarely...
- mybrid 10y ago"That's because no one even knows how to start doing "science" in this direction." No true, there is an entire field of usability science. It is all still limited to experimental learnings as opposed to theoretical deterministic knowns. Currently usability testing is only be applied to end users. There is no reason task analysis and the Jakob Neilson's 10 heuristic rules of basic usability cannot be applied to software itself. I apply the science of usability to written software.
- 11thEarlOfMar 10y agoThe highest compliment I ever heard, not paid to me, alas, was: "Your code reads like a story!"
- agentultra 10y agoWhenever 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. Dijkstra (1975) Comments at a Symposium Whenever I read code written in the "so boring it cannot fail" camp I get exhausted. This code is inherently procedural and rolls itself into a giant ball of mud -- composition is difficult to achieve so as requirements change the code accrues more loops and conditionals until it is nearly incomprehensible. It might start out neat and clean but rarely will it stay that way. Good, non-leaky abstractions are key. This can even be achieved with procedural code but I think functional programming techniques like pure functions, immutable values, and a sound type system help a great deal... even at the expense of the initial "cognitive load," it takes to learn how to employ these tools.
- DanielBMarkham 10y agoMeh. I think you're overshooting the runway a bit here. I'm a functional coder and I like the idea of reducing cognitive load. The procedural guys use it in a different fashion but if you're writing code you can't understand after walking away for a few months and coming back? You're doing something wrong. I don't think that relates to the abstraction or composability of your solution style. I find good naming, decomposition, and re-composition allows me to take things that don't matter and put them in a utility library somewhere. Then I'm left with a small number of new symbols and configurations that's easy enough to grok coming in cold. There are plenty of FP guys that don't do this. Hell if I'd want to maintain their code.
- braveo 10y agoyeah, I'm always amazed at the people who claim they looked at code they wrote 6 months ago and think it's horrible. I've looked at code I wrote 2-3 years ago, and upon examination thought to myself "that's fairly reasonable code, I got most of it right". I see people claim that means you're not growing as a developer, but my growth is about being able to build larger and more complex systems rather than perfecting small snippets of code. In other words, I've stopped caring about the specifics of code (within reason), and I get better at building systems.
- awinter-py 10y agoHire programmers who can read. Lines like "Don’t use tools that are still too hard to get a grip on" are code for 'your team will get discouraged if they have to do any homework at all to understand your project'. If that's true, how do you expect them to understand the business requirements? Every large project has embedded tools and legacy tricks so the author is implicitly saying 'don't let projects scale'. Simplicity is hard to achieve, and people who can't understand complex code can't write simple code. If a book hits you on the head and makes a hollow sound, it may not be the fault of the book.
- gaastonsr 10y agoThis is my thought. I LIKE to read clever code. Most often than not it teaches me something. Some neat way to do x. It teaches how to write terse code and I'm probably going to learn how to apply that to other areas of my code. I would be worried if my code is being reviewed by somebody who doesn't appreciate clever code. Now, clever is different than complex, or confusing code. Clever code is a neat way to do something. Complex and confusing code can be spotted immediately because it does one or many of the following things: - Functions get too nested - Tries to do too much - Function is too long - Function is not broken into logical parts - Confusing parts don't have their own function - Long conditionals - Non descriptive variable names - Modifies state all over the place And I could go on. Those are the things I would watch out for and that really take a cognitive load on me. Also, clever code is different than tricky code. To try to use a programming language quirk is crazy. You're asking for your code to be hard to read. Using a little known useful feature is good way to extend your team knowledge of a PL.
- Jach 10y agoAt the risk of making too much over the section (and ranting risks in general :)) I get the sense that "Keep your personal quirks out of it" strays dangerously close to "don't learn anything new, don't encourage the team to do it either". Of course I agree with not being clever for the sake of clverness, and not going against the overall style of the team with your preferred style. But the article goes on: "The problem is that people just want to fix their bugs and move on." Yeah, screw that, maybe if people spent some time learning better coding techniques they wouldn't have so many bugs? Take for instance this "trick": String blah = Optional.ofNullable(foo.bar()).map(Clz::doZap).map(OtherClz::extractZorp).map(OtherOtherClz::toString).orElse(""); The normal "just leave me alone and let me code and fix bugs and get on with life" equivalent is: String blah = foo.bar().doZap().extractZorp().toString(); Problem: any of those method calls can blow up with NPE, because they were written long ago by other not so careful devs and you can't simply rewrite. I see this all the time. Or a variant where foo.bar() is null-checked so they can call doZap(), but they still do (or edit it to do later) the rest of the chaining of doZap().extractZorp().toString(). When something inevitably does blow up, you get your bug to fix and then move on, but wouldn't it have been better to not have the bug in the first place? It's not even that devs don't realize that code could blow up with a NPE, a lot of the time they do, they just don't want to do the ugly "solution" up front (that someone will end up doing when they fix the bug and move on anyway) of all the intermediary variables and if scopes checking for nulls (or a NPE exception handler in the middle of their logic) and convince themselves it probably won't ever be null. The Optional 'trick' lets them be lazy (low syntax overhead once you understand what map() and flatMap() can do) and safe. Without even bringing up streams and lambdas, a nifty trick that appeared in Java not that long ago is the for-each syntax (which prevents all too easy to happen off-by-one errors in a loop counter). I keep up with language developments, I'm going to use new expressive capabilities in my code (when they're helpful -- again I'm on board against cleverness-for-cleverness'-sake) and anyone who has a cognitive load with it ought to learn it well enough so there is no load and we can develop more solid code. Ultimately I concede the point I've heard from Haskell or Scala advocates that as you practice all that Type power becomes less troublesome, I'm just not willing to invest the cognitive effort up front to get to that point since I think the tradeoffs aren't worth it for my use cases. The fact that I find a lot of Scala to be incomprehensible is a fact about my state of mind, not a fact about Scala or the developer who wrote the code. In the end these aren't even huge issues. The worst bugs aren't often the result of presence/absence of good code or capabilities (security bugs are probably a big exception), they often happen before coding even begins and accumulate over time with more and more edits to a system without stepping back to see if the original design makes sense for the current system or whether we've been stapling things together. We focus too much on these small details about how it takes 30 extra seconds to parse a too-terse line of code that would have been easier to swallow if it was 5 lines and ignore the fact that we've got 30 classes for this feature (so modular and testable) that could have been done in maybe 30 terse lines of a more powerful language with perhaps some extra cognitive overhead upfront.
- mrlyc 10y agoWhen I write code, I keep the target audience in mind. That target audience is a maintenance programmer doing their first programming job.
- JustSomeNobody 10y agoWhat's a maintenance programmer? Sounds pretty derogatory.
- klibertp 10y agoAs I understand the term it's someone who inherits the feature-complete codebase after the original author left it. The duty of such a programmer varies depending on the place and project, but it's generally someone who will be asked to fix the bugs and implement new features should the need arise. There's nothing derogatory to the term, although it's good to have some sympathy for such people - enough not to write bad code when first coding the project in the first place.
- dragonwriter 10y agoA "maintenance programmer" is a programmer whose job is maintaining a system (bug fixes and adaptation to relatively minor environmental changes) that is viewed as complete and basically static, either without major new development expected or with major new development done by separate teams in as-needed projects. Often, maintenance programmers are employed by the organization owning the system, while new development is done by contracted teams. It is a particularly common role in government and other enterprise shops, particularly those that still use a pre-Agile, civil-engineering-metaphor approach to software development.
- jacquesm 10y agoIt starts with picking the right language. Some languages help you to clarify your thoughts and some seem to do their best to obscure whatever meaning there was. Then, after you've picked your language it's up to you, the programmer. And 'good code' to me translates into 'whatever is on the screen is enough to understand the code'. If you have to page back-and-forth all the time between different parts of a function or between different functions or even different files then your code will be hard to maintain, hard to read and probably buggy. So work hard on reducing scope as much as you can.
- sqldba 10y ago"Comments are closed" says everything. The if ($null -ne $blah) one is STILL RELEVANT. In PowerShell for example it differentiates between an empty array and either retrieving an array's contents, or only the nulls from an array.
- rb808 10y agoCode 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<String>(SCOPE_PATH.split("\\.")));
- arcticfox 10y agoI'm no stickler about pretty code but whatever that is looks disgusting!
- Jach 10y agoI still hear recommendations for Code Complete so I assume it's still useful, but haven't read it myself. A somewhat old book I like is Working Effectively With Legacy Code, I think its main premise and prescriptions can help a lot of codebases out there even if not all of them, especially those in functional languages. (Namely, your codebase will be better the more you get it under test and the more you leverage OOP design principles.) Your code snippet looks like normal Java code to me. :) Not great that it's so common but it's at least not unusual... Being one line or more lines for that piece of code doesn't really matter to me but I'd prefer the single line in this case: I'm viewing it in an IDE, I've got more than 80 columns, and the pieces of syntax are easy enough to spot I don't need vertical cues. (Unfortunately rainbow parens still seem to be a minority preference.) My own quick context-free review of that: is it testable in junit? Can you substitute a mock (without using something like PowerMockito) for ScopeCoordinator.getInstance() and for Scope.getFirst()? May be better to make the instance a member variable that you can mock by just passing a different one in the constructor. Why is it Scope.getFirst(), unless this method is explicitly about finding the first of something so it's clear in context? For the 'new Path<String>(SCOPE_PATH.split("\\."))' part, that looks like it's going to be the same every time and not dependent on any runtime code so why not make it a static member? (Or an instance member you can mock, or maybe the enclosing method can take a Path as an optional param with the default being the static one.) Can the design be redone to avoid the type conversion or is it too late?
- lacampbell 10y ago
- kuharich 10y agoPrevious discussion: https://news.ycombinator.com/item?id=11992684 https://news.ycombinator.com/item?id=11992684
- tln 10y agoI always feel guilty when using idiosyncratic code. A couple of jobs ago I briefly used this questionable Python idiom: var = "%s code %s are bad" var %= "Stupid", "tricks"
- pmarreck 10y agoThe 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 http://macbeth.cs.ucdavis.edu/lang_study.pdf is IMHO indirect evidence of cognitive load issues.
- lacampbell 10y agoI'm a big fan of immutable objects. Best of both worlds in my opinion.
- pmarreck 10y agoWell, 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
- lacampbell 10y agoThe real distinction I am trying to make is that objects are a higher level, cleaner and more composable way of organising code - much more so than the "module and record" nonsense most FP people seem to push.
- bipson 10y agoThis (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. It also tackles these issues of "Gurus say" and "Everybody knows..." and tries hard to refrain from subjective matters, clearing up a few misunderstandings and old habits. 1: https://www.amazon.com/Art-Readable-Code-Practical-Techniques/dp/0596802293 https://www.amazon.com/Art-Readable-Code-Practical-Technique...
- reacweb 10y agoIMO, 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.
- jiaweihli 10y agoDRY 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).
- reacweb 10y agoYes, that is my point in giving higher priority to KISS.
- JelteF 10y agoCan this title be edited to say (2016)?
- scandox 10y agoStone 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.
- jiaweihli 10y agoWhy stop at 1 page a day? Code complete is an easy read that deserves to be enjoyed multiple times.
- Vinnl 10y ago> 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.
- sirmoveon 10y agoThe day the cognitive load is at an ideal point is the day you will lose your relevance to society, because it will be easily automated. I know that day will come; but I'm in no hurry given the current state of affairs with capitalism and a global oligarchy trying to enslave the rest of the specie. Meanwhile, I'll be happy writing obscure and complicated code that I won't have to maintain. Giving the industry leverage for the near future.
- nodex-alex 10y agoSorry but not writing some functionality just because my IDE might not be able to auto suggest it is just stupid. Writing code for anythong other than the job at hand is silly, be that for an IDE or to look cool.
- mywittyname 10y ago> Actual code from a makefile I wrote. Junior devs can’t handle overuse of new tech. Most devs can't handle overuse of new tech. It seems like the junior qualifier was put into place in order to get away with this bit of hypocrisy. The introduction of new tools will absolutely lead to increased cognitive load until the entire team is familiar with it.