I’d say it’s pretty subjective. I’m the opposite. I can’t read functions that are a hundred lines long with a dozen bound variables and half a dozen branches and early exits. That’s not easy to read and it requires keeping a notepad with you to figure out the control flow.
I much prefer short definitions with clear logic. Leave the semantics to the edges of the program where it matters. It’s easier to reason about using substitution and algebraic manipulation.
Don’t get me wrong though, I write my fair share of C code and low level drivers. For that though I tend to use a higher level language to work out the logic.
My business isn’t writing code. That’s the boring part. It’s solving the problems that is interesting.
But that’s the funny thing. Regardless we could both solve the same problems in our own ways and more often than not it will be good enough.
After twenty years and hoping for another twenty… I guess I’ve learned that what matters is that you can get along with your team and read each other’s code. Styles come and go and don’t matter that much.
I like to imagine each execution path through a function as a piece of string. The fewer strings, the fewer kinks, and the less string overall, the easier it is for my monkey brain to handle most of the time. Yes this is 'cyclomatic complexity', but strings are nicer visually :)
It does require a notepad as well when a five-page long function gets smeared across three “services”, five files and tens of functions, each doing a couple lines of code.
Leave the semantics to the edges of the program where it matters
Agreed. But when I meet this highly-structured code (and get confused), it’s usually split not across semantics, but across some random undocumented ideas about reuse, undeclared abstractions, highly indirect flow control, etc. And all of that named as if it was a most bizarre naming contest.
So that instead of a little hairy idea you get a convoluted irrational multi-plane horror to deal with.
It requires discipline to achieve what I call here, principled combination: that the combination of functions follow certain laws like they do in mathematics. In many programming languages it requires discipline because the type systems and the programming languages are not constructed in such a way as to uphold these laws for you. You, the programmer, have to enforce these laws on your code.
That is why, when I'm writing something in C, I will some times prototype my design in a higher-level language first and translate that into C code. The higher level language is more principled and helps me catch errors in the design and development stage before I've made a mess of things.
I don't always do it that way but it tends to work the best when I can get it to.
People praise typed languages, but honestly I’m much more okay with dynamic typing than with the lack of beams and pillars for design, to do any of it. It’s very easy to lose yourself for an hour and start creating a mess in what you have planned for weeks, simply because your attention was elsewhere, there was a deadline or new goals were incompatible with current ideas and you had no clue how to marry them correctly (nor courage to begin) within a timeframe available.
Add a couple of developers who aren’t you and/or switch into another project for a month or two – and it’s a recipe for a mudball. I used to believe in all that, not anymore. May be a bold claim, but most projects aren’t even hard enough to require it. I remember my own past experience and can tell that all that division into layers, concerns, etc was not a requirement nor an enhancement. I was simply ticking boxes in a “how clever do you feel this week” form. Days of work to spare five pages of clear actual instructions which could have been typed and tested in under few hours, shipped next evening and – much more importantly – I could reenter that context in few minutes after a year off, in contrast to any to-be-mudball.
Fast forward about 11 years, and people realize that having a million nested if statements and matching else blocks is actually absurdly unreadable; much better to just return early, avoid nesting, and break the "only one exit" pattern.
function doSomeStuff(input) {
if(someInvariantIsUnsatisfied(input)) {
return Error;
}
if(someOtherInvariantIsUnsatisfied(input)) {
return Error;
}
//do stuff
return result;
}EDIT: Exit the body of the guard statement, not enter.
I get you’re going for the non-standard markdown strike through, but that looks confusing and calls attention to something you meant to remove. You can (well, could) remove the word when editing.
int foo(int bar) {
int retVal = -1;
if (bar == 1) {
retVal = 1;
}
if ((retVal % 2) == 0) {
retVal = 2;
}
return retVal;
}Also, putting code inside a do ... while( false ) loop purely so you can use break as a sneaky goto to avoid deeply nested conditionals while technically adhering to the single return rule.
I think when you're starting to use control statements in bizarre ways like that, it's a good indication that maybe that's a case where breaking the "rules" is the best thing.
Especially when the code to do that depends on the amount of locals, having only a single place where you assign space for locals and a single one where you revert that helps a lot.
It also can help in languages that don’t help you run cleanup code (closing files, freeing memory) at function exit. Change the code and forget to update one of your early exits, and you have a bug. If that exit is rare, that may ship and may become a vulnerability.
https://github.com/torvalds/linux/blob/master/Documentation/...
Yes. This rule was an overreaction to a pervasive problem back in the day.
But, much like the use of "goto"s, there are times where your code is more readable, maintainable, and efficient if you ignore the prohibition. The trick is to know when that's the case.
Single Return made sense when we had to de-allocate resources, but there are few years already that most languages have memory safe resource-counted allocations (C++11 for i.e) that will free resources correctly independent of your single/multiple returns.
I don't believe that keeping those inherited "best practices" from the past will help us developing modern code.
Long life to Clean Coding!
I think it's fair to say that AbstractSingletonProxyFactoryBean[0] is something of an abomination, but it's important to avoid throwing the baby out with the bathwater. Some of the Go4 patterns like Command, Observer, Visitor, and Iterator are literally all over the place and you have to actively go out of your way to avoid writing them.
Likewise, Haskell type classes aren't something you're supposed to be implementing yourself all over the place in your application. They're very high bang-for-buck things you implement in libraries. The equivalent to implementing iterators for your collections, or AutoCloseable on resource-like java classes.
0. https://docs.spring.io/spring-framework/docs/current/javadoc...
Well, yeah, coz that's worse.
It decreases code cohesion (especially when those functions are stuck in files far away) and to little appreciable benefit.
>First, because there are no universal code principles
I think there are and good developers have a spidey sense about what they are and will usually agree but we've yet to culturally agree on what they are as an industry.
Moreover, some literature on the topic (e.g. Robert Martin) is very, very wrong.
They rather have clean, SOLID, DRY, design patterns than easy, fast, productive code.
What we have to keep in mind is that the needs of whatever codebase we're working on might be out of sync with fashion. For example, I've been relishing the recent push-back against DRY, because I think it's over-applied in damaging ways, but the main codebase I've been working on for the last year needs more application of DRY, not less.
I actually would not. I do not want to have to read every detail of each condition or formula on the first pass. I want to see high level gist of what is supposed to happen - high level algorithm. Plus, I like when variables have clearly limited scopes.
I am okay with copy-pasting code but after the second or third copy-paste, you should probably at least consider asking, “Should I abstract this into its own function?”
One copy of something is YAGNI. You aren't going to need it (an abstraction).
Two copies of something are coincidence. It's fine to copy and paste and leave it that way.
Three copies of something are finally a pattern. At least three copies are when you start to really see what sort of abstraction that you need to handle the pattern.
Another issue that's never explicitely mentionned is the vastly different calibers of programmers and engineers in the field.
I'm pretty sure John Carmack, Linus Torvald or Donald Knuth's definition of "good code" is quite different than $BODY_SHOP_RESSOURCE_1389's.
If I have a detailed, firm spec that I know won't change at all, I'd spend some time planning and then build a DRYed up, abstracted, well-tested, etc solution. I know the solution is going to be sticking around for a while, more or less, so it makes sense to devote the effort to build a solid foundation.
If the thing I'm building is squishy, looking for heavy user feedback, will likely be iterated on quickly (i.e., very agile manifesto agile), I won't spend the overhead time for those things. There's a nonzero chance the code ends up in the trashcan, and the most important thing is to ship something and get feedback from real customers. You later go back and clean it up, based on the growing confidence in the permanence of that feature.
There's a real danger in a well-intentioned clean code advocate. First, because there are no universal code principles. Maybe "have it work", but even then, a lot of value has been gotten out of code that doesn't work. And second, because it's very easy to go from a good guideline to a dogma. All you need is a few people to misinterpret your guidelines. Heck, a lot of people haven't even read the guidelines. They just parrot what someone else paraphrased on Twitter.