22 ms·
Please do not attempt to simplify this code
- rue 8y agoGod, Go is tedious to read. Also, just use a code formatter that rejects any incorrectly styled code.
- deleted 8y ago[deleted]
- pdkl95 8y agoIgnoring the initial boilerplate (license, imports) and the request to preserve the verbose ("space shuttle") style, the first line is: // Design: // // [... 4 paragraphs of English prose // explaining goals and intent... ] That's exactly the type of comment that should be at the beginning of most files!
- TeMPOraL 8y agoStrongly agreed. Wrt. comments, the more I read this file, the more I see it as a reference of how good code should look like.
- jml7c5 8y agoAs a novice programmer, I was absolutely stunned that this was not standard practice. A typical source file provides zero context, background on the subject, pointers to reference material/blog posts/books explaining the concepts, information on how it fits into the program's 'bigger picture', or (most importantly) the thought process that resulted in the file (i.e., why the choice was made to do _this_ rather than _that_, challenges faced, trade-offs, etc.). It still baffles me. Every programmer has to start from scratch dealing with a new codebase, and it makes improving any non-trivial program impossible unless one is willing to spend hours of archaeological examination. To open-source developers: if you want to get people contributing to a project (and make everyone's effort much more enjoyable!), these sorts of comments are essential. Not to mention they'll save everyone boatloads of time; it's a shame that every programmer has to piece together knowledge from scratch, rather than being 'tutored' by their peers' comments.
- adjkant 8y agoI think your desire is right, but think about this every time you create a file, and how much slower your work would be. The question then becomes: "how much commenting exactly is needed before this becomes more time than the technical debt it creates? I think this type of summary should not be per source file but per package/folder/module/project. A high-level developer overview with sufficient depth will also help stop repetition of philosophy in subsequent files. In this case, I do agree with its existence though because of both the length and complexity of the file. For many files, neither are the case.
- zeroimpl 8y agoI think this commenting only makes sense if the design is atypical. Probably 90% of the code I write is following design patterns already used throughout the code base.
- AstralStorm 8y agoAnd the 10% is unmaintained. Design patterns can tap you easily in bad designs. Usually the lost thing is performance, big way, or actual simplicity.
- AstralStorm 8y agoSince comnenter announce does not understand what I meant, it does not matter if design is typical. Functionality still has to be described, so the pattern itself buys you nothing on its own. Then the overarching idea and reasoning also has to be described to make it easier for everybody else to understand. I've met more than one codebase which tried to use a big hammer pattern to open doors. Heavy indirection to do simple things because of design choices, usually caused by a forced framework - instead of easily factorizable simplicity. Patterns should be emergent not forced. Or more specifically, the choice of appropriate pattern should be based on the problem being solved, rarely one pattern can cleanly solve all problems. Similarity is very seductive but end result is often complex and hard to reason about when followed religiously.
- nailer 8y ago
- sridca 8y agoYea, but watch how soon it becomes outdated as the file changes.
- YorkianTones 8y agoThis. Documentation (comment blocks in code, as well as all other forms of documentation) tends to become outdated because it is not maintained in sync with every code change. Solution: write clear, simple, modular code that is self-documenting and does not need extensive commenting.
- atulatul 8y agoOverall liked the original post. But also liked what you said. But here are a couple of Martin Fowler quotes (from his Refactoring book) I tend to follow: “A heuristic we follow is that whenever we feel the need to comment something, we write a method instead.” “Whenever I have to think to understand what the code is doing, I ask myself if I can refactor the code to make that understanding more immediately apparent.” https://www.goodreads.com/author/quotes/25215.Martin_Fowler https://www.goodreads.com/author/quotes/25215.Martin_Fowler
- TeMPOraL 8y agoHow soon? I've rarely seen it happen in a meaningful way (i.e. other than someone using automated refactoring on some name, and breaking some comment reference that wasn't written in a way the autorefactor tool could read). When it happens and you see it, you should fix it like any other bug. Key trick is writing comments as close as possible to the code they affect. Then it's hard to miss affected comments if one's not doing a shoddy job.
- tome 8y agoI've done it frequently myself when I've changed a line that I originally wrote myself in a way that invalidates a comment written directly above.
- dllthomas 8y ago> Key trick is writing comments as close as possible to the code they affect. Then it's hard to miss affected comments if one's not doing a shoddy job. That also helps it show up in a PR so it may be caught in code review. Even so, IME comments get missed enough that over time I can't be as confident as we'd like that they match the code. I think it's also worth calling out that this key trick is not being applied in the recommendation up-thread, which asks for a block comment at the top of the module.
- ElijahLynn 8y agoOne thing that I wish Linux kernel code had. Maybe it does but the few times I have found myself reading Linux code I go to the top and there is zero context in the comments, just a bunch of licensing information.
- dfox 8y agoThere are few linux drivers for particularly buggy hardware that are written in this style. Although OTOH what I think of is hme.ko, where the comments are more on the hillariously funny side than descriptive.
- isp 8y agoI wasn't familiar with hme.ko comments, so looked it up. https://github.com/torvalds/linux/blob/master/drivers/net/ethernet/sun/sunhme.c https://github.com/torvalds/linux/blob/master/drivers/net/et...
- AstralStorm 8y agoThe kernel code is nowhere near ideal nor "space-shuttle" code. It has a ton of single use functions which is essentially the opposite. Magic numbers and timing without explanation why. Rarely used technical descriptions such as "Lance mode". Tons of unchecked assertions on lock when kernel provides a lockdep check for this. Custom logging macros. Flies in the face of kernel "goto error" error handling convention in a few places. XXX with obvious bugs mentioned, unfixed. And more... Splitting it into more files wouldn't help at all.
- everybodyknows 8y agoHews closely to the advice offered by Go's creators: https://golang.org/doc/effective_go.html#commentary https://golang.org/doc/effective_go.html#commentary
- fogetti 8y agoSure, and then the next day the whole thing is just a long boring text which has no correlation to reality because the business rule changed and the developer next to you refactored the code.
- TeMPOraL 8y agoIf the developer next to you refactored the code without refactoring the comments, they did a shit job. Period. They need to be told to go back and fix it.
- fogetti 8y agoOr maybe the original developer who wrote the code which was so poorly written that it needed 4 paragraphs of explanation did a shitty job. Period. They need to be told to go back and fix it. You see! You argument works both ways, yay!
- TeMPOraL 8y agoOf course it does. If the comments are completely redundant with the code, they're bad. But you can't express as code why the some code is the way it is, and why it does what it does. After you tried to express in code every important information that's expressible as code, whatever important information remains must go into comments.
- fogetti 8y agoFalse dichotomy. You are trying to make this black or white while there are many more options beside comments. There are even obvious ones beside comments.
- AstralStorm 8y agoYou could. It is called an automated theorem prover, with the cheap limited version called constraint based programming. Sadly very unavailable for most programming languages. Sometimes writing the proof of why it should be like this is tricky, especially when complexity or performance is involved. (But then the tests are hard too.) Linters are essentially constraint systems for code, but not for the program.
- deleted 8y ago[deleted]
- cultofmetatron 8y agoThis is basically the style that rust sort of forces you to write in with allowing shorter forms where the compiler can automate checking that all error states are accounted for.
- nixpulvis 8y agoAnd with the beauty of pattern matching in Rust, it's usually very painless.
- startupdiscuss 8y agoThe comment:code ratio is higher than anything I write or that I’ve seen. However, it does give me some comfort. When it’s not gamed, do other HNers also feel that a high comment:code ratio probably indicates quality? There are reasons why this may be the case. (More thought, more time and a large team etc) I don’t advocate using this measure to reward anyone because it would be gamed immediately.
- lmm 8y agoI think it's likely to indicate low quality. Comments are for where the code wasn't clear enough.
- macintux 8y agoIt is rare to find code that comprehensively explains (without comments) why it exists, or often more importantly, why some superficially-equivalent code doesn’t exist there. Comments when done correctly are vital.
- mdpopescu 8y agoSo are politicians when not lying and well-behaved children. Correctly done comments are a one in a million thing. In my experience, they are utterly surpassed by "i = i + 1; // increment i" style comments. (Seriously, I'm working on code written by someone who teaches programming and he writes this type of comment.)
- AlexCoventry 8y agoIn an actual teaching context, a comment like that can make sense.
- jopsen 8y agoSome languages like golang, doesn't priorities concise code, it often takes a few lines to do something trivial. Find the object in a list with the lowest lexicographical ranked value of some property. The code to do this is simple, but not concise, leaving a comment so I can scan the function and skip 5-10 lines doing something trivial is nice.
- dmix 8y agoA code style with lots of verbose if statements? Go is the perfect language! More seriously I’ve done this style unintentionally before in JavaScript for a similar situation with plenty of branching logic. Stuff that easily could have been have the lines but not as easy to verify by hand. I’m happy to see it being formalized for certain scenarios.
- rossdavidh 8y agoWhile I can understand the basic philosophy, it seems an unfortunate example to pick something that had 2 catastrophic failures out of 135 launches. Although, I suppose, neither of them were due to software...
- zrail 8y agoThere were many other close calls, most having to do with the thermal system on the external tank, which is what damaged Columbia. It was a known issue for almost the entire program. As you said, nothing having to do with the control system.
- chvid 8y agoPorting to a language supporting exceptions would be a huge simplification. But then maybe it would stop being a space shuttle ...
- almost_usual 8y agoBetter to make blindly throwing exceptions impossible.
- geofft 8y agoA good alternative is language-level support for returning early from a function with an error. Off the top of my head, both Rust and Haskell have good support for this. (I'm sure there are others, these are just the ones I know.) Rust has a macro try!(x) that takes a Result<T, E> - a two-variant type, either a successful result of type T or an error of type E - and translates it to, if x is the first variant, evaluate the output of try! to the value of type T inside, otherwise return an error with the value of type E (on the assumption the calling function returns a Result<something, E>, too). So you can do things like `let file = try!(open(...));` and operate on the file. People liked it so much that a couple years back Rust added the question-mark operator, so you can just do `let file = open(...)?`, and chain it to `let data = open(...)?.read(...)?`. It's still visible that this is how you're handling errors, and you can always leave off the question mark and write out `match open(...) { Ok(file) => ..., Err(error) => ... }` instead, if you'd like. Haskell has its monads, which for the present purpose can be interpreted as just a wrapper type. Given a wrapped object of type T, you can give it a function that takes a T and returns a similarly-wrapped object of type U, and have it apply the function to the data. If the wrapped object is in a failure state, it can choose to "apply" the function by just not calling it at all and instead returning the same failure state. Haskell has special notation with the "do" keyword for calling several monadic functions repeatedly, where it looks like you're writing regular, imperative code and assuming errors don't happen. But again it's obvious when you're using it and you can always handle the exceptional case specially as soon as you want.
- steveklabnik 8y ago
- heyjudy 8y agoViolates title guidelines. https://news.ycombinator.com/newsguidelines.html https://news.ycombinator.com/newsguidelines.html
- chairmanmow 8y agoGuidelines != Rules. This a direct quote, so I'd think it'd be disingenuous to lowercase it. Probably good that guidelines aren't rules, even though people confuse them more than I'd like. edit: After I posted this I saw the title was lowercased and dumbed down. Unfortunate that the term 'guideline' has been misapplied again, making things worse, but at least there's some irony to get a chuckle at given the article's subject matter.
- raverbashing 8y agoSome code do require this style. If the code is complicated, sometimes it's better to make it extra explicit than just relying on the reader's comprehension (including empty else blocks, for example) Because in a nested A/B/C condition it is very easy to not notice what happens in the case where A v !B v C and/or why is it different from A v B v !C especially when some of those can't happen together (but then the code does "something" and "can't happen together" means "it will happen in that very weird case")
- munk-a 8y agoThis style of code with an emphasis on branch completeness is the biggest virtue Go gets from the lack of exceptions. I personally dislike that style since that level of detail seems extraneous for normal tasks, but when you need to write code with absolute assurances like this then preventing the stack from being unwound without an explicit return (or panic, because some stuff is just terrible) is quite helpful to inspect and insure you have full coverage.
- Ericson2314 8y agoRust's Result or Haskell's Either are wholely better for this purpose.
- dajonker 8y ago"it became clear that we needed to ensure that every single condition was handled and accounted for in the code" This is a feature of several (mostly functional) programming languages, e.g. Haskell. Fun to see that often people figure out that these types of concepts are a smart way to write your code. Too bad it usually means many people reinvent the wheel instead of learning about computer science history and other languages.
- kbumsik 8y ago> This is a feature of several (mostly functional) programming languages This is just one of a common practice of programming, not a feature of functional languages. These practices are not even "reinventing the wheel". I mean, this is obvious in many areas: from implementing complex logics like Kubernetes to making hardware drivers in C. Programming languages themselves can't automagically ensure every single conditions because these often happen outside of the program (e.g. targeting hardware state). We need to cover and test all cases by hand anyway.
- dfox 8y agoThis is one of the painfully obvious facts that tend to be totally ignored by most. Even if you formally verify all of you code it does not mean that you have covered all the possible states of the outside world. And this can mean both unexpected states on the outside and unexpected hardware failures. On one project I work with guy with significant railway signalling experience and this is one of the issues that I'm somewhat unable to explain to him. Probably because our product's design target is not to fail-fast-and-safe but fail-secure.
- topmonk 8y agoWhy do you say Haskell is an example of this? You can return undefined for anything, and have incomplete pattern matching, where if you don't mention a particular case, there is a runtime crash. An example would be head, which takes the first element of a list and throws an error on an empty list. I really love Haskell but it seems as if they are going for something different here than what Haskell provides.
- lifeisstillgood 8y agoNice. At some point one rolls up your sleeves and says "right, this part is important and needs to work and I need to be sure I have got it right" At that point space shuttle style works pretty well (usually for me I am writing some security / control dispatch for the umpteenth time)
- Klathmon 8y agoI love this! It's the "jazz music" of software development. Something which breaks all the "rules" but does so purposefully and explicitly so that it can become better than the "rules" allow. A naive look at this and my head is screaming that this file is way too big, has way too many branches and nested if statements, has a lot of "pointless comments" that just describe what the line or few lines around it is doing, and has a lot of "logic" in the comments which could quickly become outdated or wrong compared to the actual code. Yet at the same time, it's probably a hell of a lot easier to maintain and manage than splitting the logic up among tens or hundreds of files, it contains a lot of the inherently complex work it's doing to this file, and it is so well and heavily commented that it should be pretty easy to ensure that any changes also keep the comments up to date (after all, any change without changing the resulting comments should show up like a sore thumb, and will most likely prompt the reviewer to look into it at the very least).
- afarrell 8y ago> probably a hell of a lot easier to maintain and manage than splitting the logic up among tens or hundreds of files I'm only halfway through John Ousterhout's book Philosophy of Software Design but I think it agrees with you on this -- that smallness-of-file or smallness-of-function is not a target to shoot for because it prevents the things you build from being deep. That you should strive to build modules which have deep functionality and small interfaces and should contain their complexity within them so the users don't have to know that complexity.
- Klathmon 8y agoNow i'm squarely in frontend web-app development right now which definitely changes things (mainly the complexity is centered around enabling fast changes/additions to the codebase, and not the actual business logic for the most part), but while "deep functionality and small interfaces" sounds good on paper, most of the time giant files with a few functions exported aren't a good way to manage that. Sure, it solves the problem when viewed from the outside. "users" of the software (users being other devs in this case) get a nice small interface and docs that explain how to use it, but internally it's much harder to work with. Having everything in one file like this without breaking it into "sub modules" for various parts of the module means that you need to almost have a complete understanding of the module before working on it. In this case, I have a feeling that is a pro not a con. Because this file is so core to the system, and has so much complexity, that breaking it up into smaller parts could cause a dev to feel like they understand it only to find out they don't after it's released. And it means that any devs that truly do understand it top-to-bottom would just waste a lot of time switching around files if it were split up. Putting it all in the same file here nudges you to really make sure you understand it top to bottom before making any big changes. It's intimidating and scary for a reason, because at its core it is a complex piece of code, and dressing it up in "simple code's clothing" won't help.
- unethical_ban 8y agoI can't say I've written overly branchy code, but I have become a fan of leaning on the side of "verbose" regarding comments in code - specifically in nested if statements. So many in the Ops area, "just" writing scripts for themselves ( that the rest of the team starts depending on) will just pound out a script that works, with no notes on its function, design or requirements. 15 months later, they moved to a less stressful team, the app is not functioning because the servers got upgraded, and you wonder how the hell this thing works. And if it doesn't work, you have 60 hours of redevelopment to do.
- thothamon 8y agoThis code reminds me of why ML-like languages with Maybe-style types and case expressions that generate compiler errors for missed alternatives are good. I bet rewriting this in OCaml or Haskell would lead to tighter code and might even unearth a couple possible states that haven't been accounted for.
- woolvalley 8y agoYou don't really need functional languages to have those features, as swift, kotlin and others show.
- mrdoops 8y agoPattern matching would be nice in this scenario. Would help with isolating responsibility by breaking out the if statements into functions responsible only for the case they know to handle. The additional opportunities to name with more granularity could minimize the comments needed.
- arrty88 8y agoWhat's up with that tab size? Is that normal for go code?
- dmlittle 8y agoGo uses tabs instead of spaces and Github displays them as 8 character width. It can get annoying and there are several extensions to change this behavior. Tab Size on Github [1] is the one I personally use. [1] https://github.com/sindresorhus/tab-size-on-github https://github.com/sindresorhus/tab-size-on-github
- 13rac1 8y agoYes, it's Go code formatting. Spaces are incorrect. > Gofmt's style is no one's favorite, yet gofmt is everyone's favorite.
- carlsborg 8y agoThis style is common in large enterprise C++ code bases and is definitely useful when LOC exceeds a couple of 100k and the business logic complexity is high, and the project is mission critical and expected to be around for many years.
- bjourne 8y agoIs there any evidence that writing code in the demonstrated way produces higher quality? No? None at all!? Then why should I believe it? I might as well embrace healing and homeopathy too... I'd rather write my code like its written in the Linux kernel. There is no evidence that that style is better either, but at least Linus has provided loads and loads of arguments in favor of it on a mailing list.
- an-allen 8y agoI'd like to see Uncle Bob do a point-by-point critique of this... "piece of work"
- geofft 8y agoWhat is Uncle Bob's claim to fame? What has he written that is production-ready and sturdy and has held up to change? I'm sure he can have opinions - he is very experienced at having convincing-sounding opinions on software development. But where is the test of whether he's right?
- hu3 8y agoLove the guy, but he could instead write relevant software for once.
- userbinator 8y agoIf you want to see actual code that flew to the Moon: https://github.com/chrislgarry/Apollo-11 https://github.com/chrislgarry/Apollo-11
- jcoffland 8y agoAnd of course, it's nothing like the code referenced at the top of this thread.
- aerovistae 8y agoWhat is that language? edit: seems to be a custom language designed for the purpose. .agc file extension corresponds to apollo guidance computer. https://en.wikipedia.org/wiki/Apollo_Guidance_Computer https://en.wikipedia.org/wiki/Apollo_Guidance_Computer
- rzzzt 8y agoYup, AGC assembly: https://www.ibiblio.org/apollo/assembly_language_manual.html https://www.ibiblio.org/apollo/assembly_language_manual.html
- Antonio123123 8y agoRestoring original Apollo AGC https://www.youtube.com/watch?v=2KSahAoOLdU&index=1&list=PL-_93BVApb59FWrLZfdlisi_x7-Ut_-w7 https://www.youtube.com/watch?v=2KSahAoOLdU&index=1&list=PL-...
- luhn 8y agoMy favorite part from that: https://github.com/chrislgarry/Apollo-11/blob/27e2acf88a6345e2b1064c8b006a154363937050/Luminary099/LUNAR_LANDING_GUIDANCE_EQUATIONS.agc#L179 https://github.com/chrislgarry/Apollo-11/blob/27e2acf88a6345...
- booleandilemma 8y agoI also like the “trashy little subroutines” comment.
- aerovistae 8y agothis is how I wish all code looked.
- germainelong 8y agoThe comment claim that every branch is accounted for and yet few functions below you can see this is certainly not the case. They should either have fixed it first and then make such comment or shouldn't make such comment at all. Otherwise this looks a bit cringey.
- geofft 8y agoIt says "(exception: simple error checks for a client API call)" and that seems accurate to me. In particular Go (like C) has no built-in exception "throwing" / unwinding support, so for any function call where you want to pass an error onto the caller, you need to do something like result, err := try_to_get_a_result() if err != nil { return nil, err } See also https://blog.golang.org/error-handling-and-go https://blog.golang.org/error-handling-and-go . As far as I can tell, all of the if-statements without else-clauses are doing just this. (It would be nice in theory if there were better language support for making this lexically obvious but they're in a language where that's not doable.)
- germainelong 8y agoIs someone not familiar with the code competent enough to decide what is a "simple error check" and not a bug? This is very weak as they suggest that even the branches that would result in no-op are accounted for. So if someone introduce a code with a branch that is unaccounted for that automatically means the code is either faulty or is a "simple error check". With something supposedly trying to be a space shuttle worthy code the lack of definition of "simple error check" is very worrying. Would I want this code to fly me to the moon? I'd be wary.
- geofft 8y agoI think you can syntactically state that anything where the check is on the second return value (which is, by convention, the error return) is a "simple error check", and their rule for if statements is always for things that come from a first return value. For instance, this would not be a simple error check: server, err := find_current_server() if server != nil { ... } because if find_current_server() believes that it's a non-exceptional case that there might be no server at all (i.e., it might return nil, nil instead of nil and an error), then you absolutely want to handle that case.
- jackjeff 8y agoThis code would probably a lot shorter if every function call was not followed by a ‘if err != nil’ statement. This reminds me of Win32 programming.
- Jach 8y agoYou have to handle the errors somehow... though it's amusing that Go settled around what is essentially Java Checked Exceptions everywhere with the handicap of not being able to automatically propagate (or equivalently an Either type, albeit you can make expressive functional pipelines with that) so you always complect the attempt at doing work in the body, the ability to fail in the type signature, and the requirement to notice and handle the error at the immediate call site after the failure has wiped out any local state there may have been in the called function before it returned. (Hey, sometimes it's nice to have a way to force callers into something, but I want it as a design choice.) The notion of being able to fully decomplect and separate error signaling from error handling escapes both languages though, being that the notion is only as new as the '60s with PL/I or the '80s with Zetalisp (or modernly with Common Lisp)...
- iainmerrick 8y agoThis looks like pretty normal code. What is all the “space shuttle” stuff about? The only unusual things I see are a) 8-space indentation, b) lots of “if err { return nil }”, and c) lots of comments. Aren’t a) and b) standard for Go? How else is it possible to write Go code? With less verbose error handling and 2- or 4- space indentation it wouldn’t look especially “branchy”.
- Dowwie 8y agoKubernetes, eh? (strikes through its name on my list)
- marcc 8y agoWhy? Does this file/comment cause you to lose confidence in the project in some way? I'm genuinely curious to understand the reason for your comment.
- bjourne 8y agoCode that "can't be refactored" is a huge smell. This code can be written in a simpler and easier to follow fashion even if the authors of the code were unable to do so. The proof of that is the thousands of free software projects of equal level of complexity whose code bases are a joy to read.
- Dowwie 8y agoHave you ever tried to refactor code like this? They're not going to. Whatever was written is as good as it will ever get. Note that while this isn't good practice I still would adopt Kubernetes. I was exaggerating for effect.
- franciscop 8y agoOn a related note, please note that most people have the opposite issue, myself included. I know we are highly biased and tend to overcomplicate things, so I follow the KISS rule by heart. But when I do have to write complex parts of software that cannot be simplified, I will take a lot longer because I'll need to prove, first to myself, that it really cannot be simplified. Then I'll still add a big warning, either to others or to my future self (which is effectively a different person).
- _ph_ 8y agoAs much as I like the style where the code logic is commented very thoroughly, it also falls in the trap of comments no longer matching the current code, I assume some variable renaming happened. In the function (line 320 of https://github.com/kubernetes/kubernetes/blob/ec2e767e59395376fa191d7c56a74f53936b7653/pkg/controller/volume/persistentvolume/pv_controller.go https://github.com/kubernetes/kubernetes/blob/ec2e767e593953...) func (ctrl *PersistentVolumeController) syncUnboundClaim(claim *v1.PersistentVolumeClaim) error { the variable "pvc" seems to have been renamed into "claim" and "pv" into "volume", judging from the code/comment mismatch. Comments in the lines 339, 358, 360, 370, 380, 395, 411, 422, 427 point to the old names. Furthermore in line 370 the comment reads: } else /* pvc.Spec.VolumeName != nil */ { while the matching if is: if claim.Spec.VolumeName == "" { So not only the variable name mismatches, but also the comment is wrong. The VolumeName seems to be a string, so is never nil, the else comment should specify that the VolumeName is non-empty. The more verbose and detailled the comments are - the more work needs to be spent in ensuring that they are correct.
- kyberias 8y agoYes and that actually PROVES why this ultra-commenting mentality is crazy.
- yongjik 8y agoObviously I'm not the intended audience, but I'm not sure it's wise to have CloudVolumeCreatedForClaimNamespaceTag, CloudVolumeCreatedForClaimNameTag, and CloudVolumeCreatedForVolumeNameTag in the same file. This is almost the worst of both worlds: the trouble of wading through a pile of words, together with the lack of clarity.
- Etheryte 8y agoWhile I understand your sentiment, I don't think it's a real issue with pretty much any modern IDE.
- tonyedgecombe 8y agoI could imagine quickly scrolling and finding yourself editing code in the wrong function.
- joe_momma 8y agoyesss thought I was the only one that thought this style was a good idea ... Makes my last company look foolish and explains why most of the devs weren't as productive as they could have been.
- andbberger 8y agoThat sounds like some dangerous over-attribution
- joe_momma 8y agoDangerous is not delivering on time because you want the code to be fancier than it should be or needs to be when all you had to do was write it out plainly and leave obvious comments.
- crimsonalucard 8y agoSounds like a job for typed pattern matching. See rusts, match operator. The operator won't even allow your code to compile if all branches are not accounted for.
- TomMckenny 8y agoI imagine it reduces errors and I admit it's very tempting. But doesn't this style add a considerable cognitive load such that thinking several layers up becomes difficult? Perhaps there is simplified documentation of lower or mid level components so that thinking on the higher levels is not so difficult.
- jmartrican 8y agoTwo points... 1) One would have to make sure all the branches are accounted for during unit/integration tests. 2) The problem I am struggling with is the interviewers. So much of what I code I keep thinking about interviewers questioning it. "Why so many branches? Couldn't you have done this is in a more DRY manner? Couldn't you have done a better job at naming functions and variables so that so much commenting is not needed?". This thing we do is truly an art form that can more easily be picked apart than properly understood. Ultimately I think we need to be like MMA fighters... able to properly pick the correct response for the situation with no ideological preference... only results matter.
- deleted 8y ago[deleted]
- maxander 8y agoLiterate programming [0] is frequently re-invented, in various forms, because it is simply the right way to do things- and each iteration of it is almost immediately discarded, because we're all sinful and impatient creatures. [0] https://en.wikipedia.org/wiki/Literate_programming https://en.wikipedia.org/wiki/Literate_programming
- kizer 8y agoI love it so much.
- mlindner 8y agoWhy are people praising this monstrosity? Crazy complex non-simplifiable code is not good.
- contingencies 8y agoYeah, 500+ upvotes on HN apparently think otherwise, but I also dare to disagree... it's not clear, despite claims to the contrary. Comprehending this code relies on reading a long series of verbosely referenced assumptions around an implicit state machine with numerous error conditions and edge cases. The author's argument is that extreme verbosity in control structures assists with ensuring no such conditions escape an explicit code block - ie. they admit that they are (ab)using code to deal with their personal challenge of achieving a rigorous and precise conception of the problem. I would posit that approach is the wrong tool for the job, and further that they have simply failed to clearly articulate the problem, and are writing illegible code and documentation as a result. A clear symptom of the resulting fragility is the title / opening plea to others not to change their carefully constructed house of cards. Fragility does not good code make. If I were to rewrite this, the implicit state machine and its valid transitions would be documented first and foremost, eg. with a railroad diagram or ABNF. The benefit of using [a formal specification language] is that it teaches you to think rigorously, to think precisely, and the important point is the precise thinking. So what you need to avoid at all costs is any language that's all syntax and no semantics. - Leslie Lamport ... via http://github.com/globalcitizen/taoup http://github.com/globalcitizen/taoup
- mdpopescu 8y ago90% of everything is crap. This applies to both the linked code and the comments here :)
- KoenDG 8y agoAh, I love this so much.
- int_19h 8y agoSetting aside the discussion of when, exactly, this approach is appropriate, I wish we had more languages that would make it easier and more organized. The kinds of languages where e.g. code documentation is part of the syntax, where there's a way to explicitly express various contracts (e.g. design-by-contract in the language), and where, in general, the language design errs on the side of readability over terseness. Some examples (none of which are perfect) would be COBOL, Ada and Eiffel. But they all have their own issues, and then of course there's a question of long term support and maintenance.
- z3t4 8y agoSimplifying or not, having unit tests that cover all branches will become handy.
- nradov 8y agoFor background on how actual Space Shuttle flight control software was written I recommend reading the "NASA Manager's Handbook for Software Development". It contains some great guidelines for writing safety-critical software. AFAIK, no Space Shuttle mission ever suffered a serious safety incident due to a software defect. https://ntrs.nasa.gov/search.jsp?R=19910006460 https://ntrs.nasa.gov/search.jsp?R=19910006460
- dustycat 8y agoThank you for the link. Could people who have studied it answer whether it is similar to the code here?
- thegabez 8y agoDRY is one of the most overly used of the software adages. It more often leads to premature abstraction and overly complex code. My personal preference is explicit code.
- nickharr 8y agoHaving spent 25+ years writing, viewing, commenting on and reviewing code in a multitude of languages, this is good stuff to see - regardless of the 'style' of programming (or the language broadly-speaking). Stepping back and whilst we can all overlook it, good code comments can make an enormous difference in productivity - both for an individual, a team and indeed a business. It aids repository knowledge (something that is easily lost between current and prior teams/individuals), which shouldn't be mistaken for the intelligence of someone looking at code... I've spent far too much time personally and otherwise attempting to reverse-engineer code written by someone with no comments or explanation. At times, super experienced programmers/developers will take performance-enhancing shortcuts that the less-experienced don't understand; They'll compress routines and functions that are a result of their explicit knowledge of a language and/or domain but without explanation... On a basic level, comments should: inform, educate, outline and help others understand the sometimes complex routines and functions that we all create and often under an enormous amount of pressure. There are those that believe good code shouldn't need explanation and to some degree that's true, but you can't apply that brush to every codebase. Code can become complex, awkward, spaghetti-like and almost unfathomable at times. I've always strived to teach less experienced developers to comment well, efficiently and with a little humor/humour (where possible); Something that allows us to understand code quickly, appreciate the efforts of those before us and smile/grin at the complexity of a challenge. Personally, I don't really care about the code/comment ratio - It's a complete red herring. At times, code comments can be worth more than the code itself. At other times, they just help you get your job done; quickly, efficiently, no fuss, just great code.
- lmm 8y ago> There are those that believe good code shouldn't need explanation and to some degree that's true, but you can't apply that brush to every codebase. Code can become complex, awkward, spaghetti-like and almost unfathomable at times. I have yet to find a codebase that couldn't be made clear as soon as a programmer actually put some effort into doing so. Far too often adding a comment is used as an excuse to give up on making the code readable before you've even started.
- 8y ago
- dymk 8y agoctrl+f 'err != nil', 88 matches
- edoo 8y agoI wonder if this arises there because people get moved and would otherwise receive lots of clarification requests regarding the implementation from a new maintainer. It is easier than maintaining a separate wiki page that might lose track of changes.
- j45 8y agoSpace shuttle coding is like preparing code for your future self to quickly make sense of. A key part of the software lifecycle is being able to easily onboard newcomers to be productive, or coming back to a part of a code base months, or even years later.
- Groxx 8y agoif claim.Spec.VolumeName == "" { // ... } else /* pvc.Spec.VolumeName != nil */ { maybe some cleanup actually would be a good thing.
- apo 8y agoOne simplification that might be tempting is to replace the "if !condition" with "if condition". For example, line 463 shows: if !found { // handle missing } else { // handle found } I would simplify this to: if found { // handle found } else { // handle not found } Or even: if missing { // handle missing } else { // handle not missing } The test-negative style is repeated throughout the file, but inconsistently. Sometimes the negative is tested in the if branch, sometimes it's tested in the else branch. Why?
- gtrubetskoy 8y agoMy guess is that this is in line with the Go tradition of first handling all the odd cases leaving the essential part of what the function (or block of code in this case) attempts to do as the last part. So "if !found" to me suggests that this is more of an exception than the rule and this is why the code is written so as to deal with it first.
- AgentME 8y agoMaybe they always put the standard path first, and the negative `if !found {` lines are places where `found` is usually false.
- kannmig 8y agoReminds me of the classic SICP quip: "Programs must be written for people to read, and only incidentally for machines to execute."
- vips7L 8y agoHN: this is amazing! Everyone should be writing code like this! Also HN: c++ and java are awful! They're so verbose and I have to type so much!
- yawaworhtttt 8y agoWhat if I actually wanted the ability to get a thing going and quickly working within a few lines, while also being able to spell things out as needed when the use case arises? Crazy I know.
- lincpa 8y agoI tend to wrap the if statement in the function as much as possible, so that the code as a whole presents a sequential pipeline structure. Keep the code concise and readable. MyBlog: The Pure Function Pipeline Data Flow https://github.com/linpengcheng/PurefunctionPipelineDataflow https://github.com/linpengcheng/PurefunctionPipelineDataflow
- deleted 8y ago[deleted]
- openloop 8y agofine jesus.
- quotemstr 8y agoThis kind of pattern indicates that the underlying language has inadequate metaprogramming facilities. You should be able to robustly verify certain guarantees via the type system instead of relying on a specific code formatting convention to do it.
- hannofcart 8y agoI see a lot of comments mentioning various versions of the following: - "It's the "jazz music" of software development." - "...breaks all the "rules" but does so purposefully..." - "this is irreducibly complex, and cannot be split into multiple files" - "that smallness-of-file or smallness-of-function is not a target to shoot for" I am wondering: can't all the above statements be said in defence of any poorly engineered, gargantuan single page code?
- pknopf 8y agoCan everyone play jazz? No.
- hannofcart 8y agoOnly because you asked: https://youtu.be/cRzDEdY8FL4?t=214 https://youtu.be/cRzDEdY8FL4?t=214
- andyfleming 8y agoI thought your link was going to be to "H. Jon Benjamin Doesn't Play An Instrument, But Recorded A Jazz Album": https://www.youtube.com/watch?v=ZeMIgcNUpNQ https://www.youtube.com/watch?v=ZeMIgcNUpNQ
- fogetti 8y agoCan everyone claim that their terrible music is jazz music? Yes.
- pknopf 8y agoApart from a comedy bit, can everyone easily spot the difference? Yes.
- kstenerud 8y agoNo. Most jazz, including by the jazz greats, just sounds plain terrible. The worst is jam sessions, where everyone steps over each other but it sounds not abysmal at times because they're in the same key.
- mindcrime 8y ago1. Every 'if' statement has a matching 'else' (exception: simple error I've always considered this a best practice. There's rarely a good reason not to have a matching else, even if it's no more than a comment reading // intentional NOP or logger.trace( "THING didn't happen, ignoring." ); Either one tells anybody reading the code that the else case was thought about and handled the way it was for a reason.
- casper345 8y agoAlthough I think this is great, this reminds me of a talk Bryan Lunduke did where he says CS/software development is not a profession yet. I love the flexibility software devoplmentgives to every cs, programmer, developer but when you think more about it, that is not the same for other jobs/professions. Professions have standard guideline, procedures to follow. Everyone is doing any language they want, design patterns they just read from a random article, 100s of tutorials on one subject. But are all languages/paradigms/architecture equal? Should there be language only used in some industries to keep consistency? Doctors can't just try a new technique, neither do lawyers. Not saying it is bad, but something I think more thought needs to be put into.
- fogetti 8y agoI would say that "Everyone is doing any language they want, design patterns they just read from a random article, 100s of tutorials on one subject" is far from being true anyway. That might be true if you live in a cave but when you are working on a team of 6-8 people with a team lead then basically none of that is true and you are forced to follow others' decision and everything is decided for you (instead of you to make decisions) no matter if you like it or not. Of course some might say but then you have to make compelling arguments to raise your concerns and being heard but that's beyond the point and that's politics that most people (including me) despise. As a software engineer your only choice to make those decisions you mentioned is that you are a manager of some sort or you work completely alone. And for some reason most developers accept this hierarchical relationship in their daily professional life but still pretend that they are allowed to make decisions by themselves instead of pointing out the implicit forces which rule their daily lives. And I like to call out this line of thinking because it is pushing this liberal agenda that you are the sole reason for your luck or failure which is not true at all. Not even close to reality. Actually many thought leaders in our industry for example Uncle Bob anticipate that our industry MUST and/or WILL be regulated (if by self-imposed regulation or external one is again beyond the point) otherwise the whole industry would lose credit. And I fully agree with that. Not only because of credibility reasons but also because it makes the implicit subordinate relationship that most developers are blissfully unaware of, more explicit.
- unnouinceput 8y agoIf you ever programmed embedded software for big companies (automotive, medical, etc) you're used to this style. Hell, at Siemens we were forbidden to even use ternary operator, a rule said it was to be replaced by a complete if/else statement no matter what.
- taeric 8y agoI've already seen a few places where this is compared to literate style programming. I agree and can see the comparison. However, a main draw of literate style, as used by most tools that support it, is precisely that it lets you bend the code around a narrative. Instead, this is having to fit a narrative to the code. As an example of what I mean, look at some places where the if chunk is as big as the else chunk. By the time you are at the else, you might have to scroll back a ton to get to what it is you are in the else of. Now, yes, to an extent, you could split this between functions. Such that you could have: if foo { doSomething } else { doSomethingElse } Literate style, though, would be more akin to if foo { <<since we have a foo, we can ...>> } else { <<Without a foo, we have to ...>> } This is somewhat subtle, but not having to define everything in terms of functions with inputs and single outputs can free certain parts of your code to just dealing with the core logic that you care to explain. Not a panacea, but can be quite powerful.
- whoisthemachine 8y agoI would argue that if they had solid unit tests of the expected behavior for their `pv_controller`, they wouldn't need this level of documentation - nor the scary space shuttle warning - the code would self-document.
- boramalper 8y ago> Space shuttle style is meant to ensure that every branch and condition is considered and accounted for… FTFY: …hopefully! Only if they’ve used a language with Algebraic Data Types support, the compiler would enforce that “every branch and condition is considered and accounted for.” The only PL with ADT that I’ve used was Haskell, but I’ve heard that Rust has them too “enums”. People are arguing that “code is what computer executes, comments don’t ensure anything!” and so on, but besides being executed, (this Go) code does not ensure anything either. It’s human eyes that skim through all the cases, and look for a matching branch for every one of them that “ensures.” In my humble opinion, this so-called “space shuttle style” is just one of the many workarounds to deal with Go’s by-design limitations (the most famous one being lack of generics), a language that’s designed only 9 years ago.
- vijaybritto 8y agothere is a discussion for generics in 2.0
- weberc2 8y agoI agree with this, but snarky comments like these neglect that ADTs (or generics) are not the only nor remotely the most important factor in choosing a programming language. Go certainly bests Haskell and Rust in many important areas even if it loses in safety.
- boramalper 8y agoI wasn’t trying to trash Go! Two years ago I’ve moved one of my biggest projects from Python 3 to Go because my program was inherently concurrent, and at the time -and I think still- Python has 3 competing approaches for concurrency: threading, multiprocesses (for parallelism), and asyncio. Although it’s nice to have a variety of options, I think this balkanisation affected the community in negative ways because the options are not compatible with each other (see the emerging “SansIO” libraries for asyncio). This is actually the reason why Python gets so much praise: thanks to its standard library, there is often a single canonical way to do something (if you need sets use `set`, if you need matrices use NumPy, …), which means that the vast majority of libraries are interoperable* with each other. Same goes for Go when it comes to concurrency, and that’s what guided my choice. *: high cohesion, low coupling
- gigatexal 8y agoThis is awesome. I have learned a ton about the volume controller just from the comments!
- portal_narlish 8y agoThis seems psychotic. Why not put the same energy into rewriting this code correctly in a statically typed functional language?
- discobean 8y agoI find I often write code in comments first w/ the business logic, and then flesh out the comments with actual code.
- shriphani 8y agosomeone please introduce idris to the k8s team.
- jonahx 8y agoGood: High-level comments that provide context, history, and motivation for the current design. Also good: Line comments that explain cryptic details (eg, the semantics behind bit manipulations) or link to things like protocol definitions. Bad: Line comments that simply repeat what the code does.
- RickS 8y agoAs a fairly junior programmer, I'll play devil's advocate on the Bad bit – I find that kind of thing very helpful sometimes. Having plain english demarcations for what a piece of logic does – or where in the loop something is – can shave 80% off the time it takes to get reacclimatized when needing to make a quick change. There are moments when I know the conceptual bit that needs changing, and would prefer to hunt it in english rather than spend time translating on the fly.
- jonahx 8y agoTwo relevant points here: 1. My comment assumes the code itself is well-written and clear. If it is, the plain English explanation will be superfluous, and you'll be able to understand the code just as fast. If it's not, then the comment was the wrong solution to a real problem. The correct solution is to rewrite the code. 2. What counts as "well-written code you can understand instantly" is of course experience-dependent. And not just "years of experience" dependent, but primarily "familiarity with the paradigm and style of coding experience" dependent. Steve Yegge talks about over-commenting by junior developers here: http://steve-yegge.blogspot.com/2008/02/portrait-of-n00b.html http://steve-yegge.blogspot.com/2008/02/portrait-of-n00b.htm... I don't include that to be insulting, but because it tracks with my own experience as well.
- tzjmetron 8y agoThe amount of circlejerking in this thread is unbelievable. Go is a horrible language, and if this code were posted anonymously, these same idiots calling it "the jazz music of software development" and "space shuttle style" (copied verbatim from the actual code comments to boot) would be deconstructing and denigrating it to the last fine detail. Hilarious.
- peter_retief 8y agoWay easier to maintain code that is verbose, I have never been a fan of abstracting functionality with the purpose of having less code to read
- mdpopescu 8y agoYes, I too like to send my own electric signals to the parallel port instead of using the print menu from Word. /s
- peter_retief 8y agoWithin reason
- viach 8y agoHow about: code should be self-explainable, functions should not take more than a screen, ensure behaviour with tests. Otherwise, to me it looks more like Space Shuffle style.
- Xyik 8y agoLove this thread. I see this a lot, where engineers blindly follow best practices and have urges to re-factor code when its not necessary. Big files are not necessarily bad and I love that a lot of the comments are with me on this. Having to open several tabs and remembering where you are in the stack can be hard once there are more than a couple of frames / function calls in. There is a lot of benefit to keeping logic in 1 file or 1 function, and there is a time and a place for writing really granular DRY code. As with all engineering, there are always trade-offs to every decision and I think its about time we put to rest some of the traditional rules of thumbs and 'code smells' new engineers learn and adhere to like a bible.
- jonahx 8y ago> As with all engineering, there are always trade-offs to every decision This is the cliche that needs to be put to rest. Yes, often there are tradeoffs. But just as often one thing is better than another thing, and there is no tradeoff. A worldview in which everything has pros and cons and is ultimately subjective is fertile ground for entrenched habits, because it means never having to admit you're plain wrong, that there is a better way, or that other approaches are simply that much better than yours.
- xendo 8y ago> everything has pros and cons and is ultimately subjective That sound's awfully like postmodernism which is terrible everywhere it's applied, not only programming.
- Xyik 8y agoI believe code design is ultimately subjective. Unlike other metrics like performance which can be easily and definitively measured, you can't easily measure 'good' code. The definition of 'good' changes based on the context of the code base and function the code is trying to achieve. In this case, choices like having giant functions and files is definitely subjective.
- jcoffland 8y agoThe code referenced here is extreme. It does not consider diminishing returns or acknowledge tradeoffs in readability. I would advise a more balanced approach. A more compact style allows more code to be viewed at once making it easier to understand. Of course, taken to the other extreme, overly compact code becomes hard to read. It's called, "the art of computer programming", because blindly applying programming principals rarely yields good results.
- yoz-y 8y agoHonestly, to me this looks like normal good code. It reads from top to bottom, exits early, does not have conditions so long that they require lines to be wrapped, it has function that are long or wide but not both... Does not seem to superfluously refactor code into functions called only once. Maybe there are too many comments, but for code that is critical and might be harder to understand at a glance that is better.
- hinkley 8y agoThe longest functions don’t follow the same guard clause style as many of the shorter functions and I think that’s a mistake. That half the file avoids else clauses and half don’t tells me there’s an argument here that was never adequately resolved. I think we’re missing about six functions and a couple more refractors, then tone down the a couple parts of the lecture. As it is it’s obvious that many different hands were in it (and if you look at git blame, one of them doesn’t know how to revert changes properly and needs to stay after school for extra lessons. If this file is so important it shouldn’t have the most critical lines with a “revert changes” comment as the commit message. You done goofed, son.)
- throw-far-away 8y agoIt's a code smell whenever a function doesn't fit on a page or has more than 2 levels of indentation. Smaller functions are easier to test, easier to read and easier to debug. Leviathan kitchen-sink functions are a sign of slap-dash engineering.
- spullara 8y agoMy take away from reading this code is that it is a huge mess that may be impossible to clean up. At some point they failed to introduce abstractions that would remove the need for all this complexity. They are probably right that now that it works that it will be hard to refactor it without leaving out some critical case. However, I pity anyone that works on this code base.
- kierenj 8y agoWould you agree that sometimes, abstractions can just distribute and hide complexity whereby actually all of that context is needed to comprehend the algorithm or process at hand (some things just ARE complex)? In this case right here, what's your counter-example, or what would you use instead of their specific approach?
- lmm 8y ago> Would you agree that sometimes, abstractions can just distribute and hide complexity whereby actually all of that context is needed to comprehend the algorithm or process at hand (some things just ARE complex)? No, or at least not often enough to be worth thinking about. It is of course possible to use abstractions badly, but the problems that business software has to solve are always fairly simple because they're human problems; human business processes were never that complex. So if a program looks really complicated, the overwhelmingly likely cause is failing to use appropriate abstractions. > In this case right here, what's your counter-example, or what would you use instead of their specific approach? As others have said, a result type would greatly simplify this code without sacrificing any safety. No doubt after such a simplification made the code shorter and easier to comprehend, further simplifications would become apparent.
- femiagbabiaka 8y agoYour metaphor doesn’t really apply — this isn’t business software, it’s part of a distributed job scheduler. That is inherently complicated. There is of course an open argument of language choice, but I think there’s something to learn from the lack of software built in $BETTER_LANGUAGE. It’s also an open source project, so if anyone wanted to throw up a branch with an example of simplification without sacrificing logic branch completeness that door is open. Code might even convince the k8s team to change what you think is misguided behavior.
- zerr 8y agoSeems like a horrible spaghetti code to me - and the verbose commenting doesn't help.
- emmanueloga_ 8y agoThis looks like an example of why I'm trying to learn more about model driven development these days. There's probably a lot of wisdom in this file embedded in a lot of noisy Go code. If someone tries to implement this code in a different programming language, a lot of this wisdom would have to be painfully extracted from the Go code. Some sort of extracted decision table format (examples [1]) would be objectively easier to read, could be rendered in different formats, hyperlinked, etc. Maybe a small subsection of this code could be generated from some structured data specification. Mbeddr [2] is an example of a language that allows embedding decision tables directly in C99. It can also embed state machines and other goodies directly into the code. This is just one way to go... I'm sure some ppl would complain about lock-in in a specific IDE. It is not clear to me exactly which domain driven techniques could be applied to this particular piece of Go code, but it could be worth it to find that out. From what I see out there model driven design seems to be applied to areas were really convoluted, and some times nonsensical logic needs to be mapped to code, like in insurance policy management, and stuff like that, or for other complicated code like firmware, drivers, protocols, etc. Why can't we apply these techniques to general programming problems? 1: https://medium.com/@markusvoelter/the-evolution-of-decision-tables-80ce77bf984c https://medium.com/@markusvoelter/the-evolution-of-decision-... 2: http://mbeddr.com/index.html http://mbeddr.com/index.html
- known 8y ago"premature optimization is the root of all evil" --knuth
- vectorEQ 8y agothis is how my code looks until it's done, where i take out all of the nonsense and make it unmaintainable, shooting myself in the foot for any development i need to do on it in the future. love it :D
- AstralStorm 8y agoReadability is not a valid requirement as it does not specify a valid end condition. Likewise simplicity is not a valid requirement. Code coverage by tests, proofs and comments is. A valid requirement could be considered complexity, number of names and entities and a lot of other linter constraints. Heck, aggressive deduplication is not even always good. Self similarity is not necessarily good either (the reuse of patterns) as you could have problems trying to spot the differences and special cases as they may no longer stand out.
- revskill 8y agoWhere's the test ? How people test this piece of code ? Test is what matters, automatic or manual.
- alecco 8y agoFor a whole codebase like this check out SQLite. The best one in the world.
- cal97g 8y agoThis is all Golang is good for.
- danielovichdk 8y agoThe key thing about complexity is that, you can move it around, but you can't make it go away. The complexity has to be there, somehow. It's also highly subjective how one sees and grasps complexity. Breaking code up for the purpose of reducing complexity is more often a symptom of clearing your mental space. But IMO most often, complex code is much more well off being put in the same place, and with extensive comments too. I also believe it's a true flaw to believe that a lot of comments are unnecessary when writing "important" code. Comments are written in a human language, we interpret them as such. Computer language is different and it takes, more often than not, more mental power to understand and more important to change.
- preordained 8y agoThe hubris in some of these comments is staggering. No, you wouldn't have more cleanly (and successfully) written this in $BETTER_LANGUAGE, even with your super power of perfect hindsight.
- dangom 8y agoInteresting to run a "blame" on this code, and see that almost every line has been touched by a different commit, and that 41 contributors collaborated on the file. It seems that the "do not attempt to simplify this code" is necessary rather because the cost of having so many people relearn what they already know is too large, and not because the code itself cannot be written in a simplified manner. It's a beautiful example of the difference between real-life constraints of a codebase developed by multiple collaborators, and the elegance that we strive for when coding alone. There is no "one size fits all" coding style in software engineering.
- hopler 8y agoPeople seem to be missing that "simplify" here is a droll insult to too-clever hackers. The code is not too complex, it is well written and documented.
- tomphoolery 8y ago> Space shuttle style is meant to ensure that every branch and condition is considered and accounted for I thought this was what you were supposed to do. Not that I do it every time, because I'm lazy, but Zed Shaw used to say every `if` conditional should have a corresponding `else` (which can also take the form of guard clauses). In Ruby, this is really easy to do because every method has to return something, so you build "returning nil or some String" as a concept into your program. There's a whole discussion around whether _that_ is a good idea, but I digress...going through the motions of enumerating every possible condition for a given piece of logic is not a bad exercise, and can result in very robust code at the expense of the code looking a bit more confusing than necessary. We have a very similarly-written piece of code to this in our eCommerce platform. This code, written in Ruby, is used to calculate prices of discounts with regards to discount compatibility. There's a big warning atop the method stating something like "Please don't decorate/override this unless you ABSOLUTELY need to, the consequences could be very difficult to debug!". Not the easiest piece of code to look at, but it gets the job done in an efficient way without having to rely on C extensions for performance. We were also focused on correctness here, because calculating the wrong discount group could result in zero or even negative order totals, which our clients would _not_ be happy about. So the code is very verbosely written, isn't optimized for legibility, and strictly specifies both if and else sides of each conditional.
- rkagerer 8y agoShuttle's missing a space after the comment symbol //checkVolumeSatisfyClaim checks if the volume requested by the claim satisfies the requirements of the claim
- amai 8y agoIsn't this code style just a sign that go is lacking proper exception handling?
- boomlinde 8y ago// 1. Every 'if' statement has a matching 'else' (exception: simple error // checks for a client API call) Comment rot? The code is filled currently with else-less if statements, not only for error checking.
- fogetti 8y agoObviously there are many people on HN that consider that to be a good thing. I personally agree, this is the typical comment got. Only obviously blinded people wouldn't see this.
- boomlinde 8y agoI don't think that anyone here believes that comment rot is a good thing, or that they are particularly "blinded". I just think that the fact that the comments lie is a compelling argument against the prose comment-heavy style used in this file. In this case it was not a big one because it's trivial to determine that the comment is not true, but in general I think that no comment is better than the wrong comment. I have not cared to read the file much further so I can't comment on whether comment rot is really prevalent. Actual "space shuttle code" is AFAIK built to satisfy a specification, not to serve as a specification in itself. When you find that the specification is lacking or somehow faulty, you get the people responsible for it to revise it, wait for the new revision and adjust the code to match. The key is that they are two separate processes. Someone responsible for the specification doesn't need to be concerned with the exact details of the implementation, and those responsible for the implementation only need to be concerned with satisfying the specification. When the specification and implementation is all mixed up as prose and code in the same file you don't get to enjoy the benefits of separating those concerns. Changing the spec is the same process as changing the code, and the order of change is indistinguishable. You can change some code, but then you have to find all the references to the code you changed in the prose and adjust that too. You can change the prose, but then you have to adjust the code accordingly and any prose that assumed that the code worked as before. You'll be relying on tests and reviews (reviewers suffering the same drawbacks as the submitter) to enforce this, which IMO isn't not necessarily a bad thing, but not exactly rigorous enough to give a "space shuttle" stamp.
- toastking 8y agoThis is pretty smart given the nature of open source. It's a good safeguard for someone messing with code that runs like half of cloud deployments now.
- Lapsa 8y agoemm... no, please. like the enthusiasm though
- eigenloss 8y agoThis is not compliant with the JPL/NASA Coding Standard: https://lars-lab.jpl.nasa.gov/JPL_Coding_Standard_C.pdf https://lars-lab.jpl.nasa.gov/JPL_Coding_Standard_C.pdf Calling this "Space Shuttle Style" is an appropriation of credibility and an insult to the engineers of STS.
- ArchTypical 8y agoOf course this can be improved and simplified. Handling 12123123 err checks is a problem of avoiding short circuit failures. That's fine, but you have multiple return values, so there's no reason not to leverage that properly...or even consistently. The whole file is littered with waiting assignment until a comparison, except in some cases or where if and elseif statements use the return values inline but not other places. It's just random. //checkVolumeSatisfyClaim checks if the volume requested by the claim satisfies the requirements of the claim func checkVolumeSatisfyClaim(volume *v1.PersistentVolume, claim *v1.PersistentVolumeClaim) error { // check if PV's DeletionTimeStamp is set, if so, return error. if utilfeature.DefaultFeatureGate.Enabled(features.StorageObjectInUseProtection) { if volume.ObjectMeta.DeletionTimestamp != nil { return fmt.Errorf("the volume is marked for deletion") } } volumeSize := volume.Spec.Capacity[v1.ResourceStorage].Value() requestedSize := claim.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)].Value() if volumeSize < requestedSize { return fmt.Errorf("requested PV is too small") }elseif v1helper.GetPersistentVolumeClass(volume) != v1helper.GetPersistentVolumeClaimClass(claim) { return fmt.Errorf("storageClassName does not match") } // function here, obviously err = volumeAccessModeChecks(volume, claim) return err } // Here's the function func volumeAccessModeChecks(volume *v1.PersistentVolume, claim *v1.PersistentVolumeClaim) error { // even the naming sucks. DISTINCT case error name isMismatch, volumeModeErr := checkVolumeModeMismatches(&claim.Spec, &volume.Spec) if err != nil { return fmt.Errorf("error checking volumeMode: %v", volumeModeErr) }elseif isMismatch { return fmt.Errorf("incompatible volumeMode") }elseif !checkAccessModes(claim, volume) { return fmt.Errorf("incompatible accessMode") } return nil } This whole function is already a separated function from the middle of the file, no reason to stop there. No need for separate files when the function calls are going to be distinct and inline beneath their usage.