by stcredzero · 9y ago · 0 comments
This is what happens in almost every language. Niftyness and the prospect of impressing your coworkers distorts the cost-benefit calculation. This is in addition to the true costs appearing months or years after the code is written, involving the interaction of complex factors, like increased cost of debugging.
"Clever" should be regarded as a limited resource. Also, the shop should encourage a culture where "clever" with regards to making code easier to understand should be valued above all else.
EWD 340 (Prof. Edsgar Wybe Dijkstra) [1]:
"The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility, and among other things he avoids clever tricks like the plague. In the case of a well-known conversational programming language I have been told from various sides that as soon as a programming community is equipped with a terminal for it, a specific phenomenon occurs that even has a well-established name: it is called “the one-liners”. It takes one of two different forms: one programmer places a one-line program on the desk of another and either he proudly tells what it does and adds the question “Can you code this in less symbols?” —as if this were of any conceptual relevance!— or he just asks “Guess what it does!”. From this observation we must conclude that this language as a tool is an open invitation for clever tricks; and while exactly this may be the explanation for some of its appeal, viz. to those who like to show how clever they are, I am sorry, but I must regard this as one of the most damning things that can be said about a programming language. Another lesson we should have learned from the recent past is that the development of “richer” or “more powerful” programming languages was a mistake in the sense that these baroque monstrosities, these conglomerations of idiosyncrasies, are really unmanageable, both mechanically and mentally. "
[1] https://www.cs.utexas.edu/~EWD/transcriptions/EWD03xx/EWD340...
"I see a great future for very systematic and very modest programming languages. When I say “modest”, I mean that, for instance, not only ALGOL 60’s “for clause”, but even FORTRAN’s “DO loop” may find themselves thrown out as being too baroque."
While I agree with the general sentiment, it's very important to take anything Dijkstra says with a huge grain of salt. He was a mathematician first and foremost. He obsessed about things like a mathematician. Such people, while very smart, make for very unproductive software engineers. They also have a way of sounding deceptively smart and thoughtful, when really they're just talking out of their ass. Beware.
Without qualification, Dijkstra was one of the greatest computer scientists in our field's short history. While I don't agree with every single one of his ideas, I would encourage budding computer scientists and professional programmers to look over what he accomplished. He most certainly was not unproductive.
Wikipedia says that Dijkstra is known for:
- Dijkstra's algorithm (single-source shortest path problem)
- DJP algorithm (minimum spanning tree problem)
- First implementation of ALGOL 60 compiler
- Structured analysis
- Structured programming - Semaphore
- Layered approach to operating system design
- T.H.E. multiprogramming system (one of the first operating systems)
- Concept of levels of abstraction
- Concept of layered structure in software architecture (layered architecture)
- Concept of cooperating sequential processes
- Concept of program families
- Multithreaded programming
- Concurrent programming
- Concurrent algorithms
- Principles of distributed computing
- Distributed algorithms
- Synchronization primitive
- Mutual exclusion
- Critical section
- Generalization of Dekker's algorithm
- Tri-color marking algorithm
- Call stack
- Fault-tolerant systems
- Self-stabilizing distributed systems
- Resource starvation
- Deadly embrace
- Deadlock prevention algorithms
- Shunting-yard algorithm
- Banker's algorithm
- Dining philosophers problem
- Sleeping barber problem
- Producer–consumer problem (bounded buffer problem)
- Dutch national flag problem
- Predicate transformer semantics
- Guarded Command Language
- Weakest precondition calculus
- Unbounded nondeterminism
- Dijkstra-Scholten algorithm
- Smoothsort
- Separation of concerns
- Program verification
- Program derivation
- Software crisis
- Software architecture
This quote by galactipony is really offensive to me:
> Such people, while very smart, make for very unproductive software engineers. They also have a way of sounding deceptively smart and thoughtful, when really they're just talking out of their ass. Beware.
It is quite clear to me that Dijkstra wasn't "just talking out of [his] ass."
Learn more about Dijkstra at https://en.wikipedia.org/wiki/Edsger_W._Dijkstra or in any resource on the history of Computer Science.
I didn't say Dijkstra was talking out of his ass in this case. I'm saying you often can't tell when people like him are talking out of their ass, as they sometimes do. Who would think the inventor of all these algorithms would ever utter a half-formed thought, on a whim? Unthinkable! Yeah... no.
Another distinction you fail to see is that somebody who is great at finding the best or optimal algorithms (i.e. a great theorist) isn't necessarily a productive programmer. To the contrary, perfectionism and productivity are at great odds.
Dijkstra was heavily at odds with real-world programming as it was done, to the point of isolating himself with his work. If we followed his opinions on how to program, we wouldn't get much of anything done.
But, lets discuss the 'for clause' and 'do loop': these constructs were made specifically for one kind of simple loop. It is not a systematic solution for an iterative process. To me it seems Dijkstra specifically aims for languages such as LISP (which, with the renewed interest from Clojure is one of the most oldest successful (semi-) functional programming languages).
It still seems intellectually dishonest to leave it out. Clearly, what Dijkstra in 1972 considers too "clever" may in fact be tools that are now basic building blocks of everyday software. We can all agree that "too clever" is bad. We can't agree on what "too clever" is.
"But, lets discuss the 'for clause' and 'do loop': these constructs were made specifically for one kind of simple loop. It is not a systematic solution for an iterative process."
I'm fairly sure (from what I remember him writing) that he doesn't like it because you can do the same thing with existing constructs, so you'd be adding complexity to the language that isn't strictly necessary. History has shown that actual programmers prefer having for loops like Algol.
"To me it seems Dijkstra specifically aims for languages such as LISP (which, with the renewed interest from Clojure is one of the most oldest successful (semi-) functional programming languages)."
Probably not, or else he would've talked about LISP in a different manner (he does talk about it in an earlier paragraph).
-- Alan Kay, The Computer Revolution hasn't happend yet — 1997 OOPSLA Keynote
Alan seems to make an overly broad statement, which is funny, but also weak.
I know I'm preaching to the choir here. I know we've all come back to our own code six months later and had to puzzle it out.
More on cleverness from an old AI textbook (Artificial Intelligence Programming by Charniak, Riesbeck and McDermott):
"1.12.5 Cleverness
Avoid it . Clever tricks ... [Lisp specific stuff omitted.]
To paraphrase Samuel Johnson, we advise you to look over your code very carefully, and whenever you find a part that you think is particularly fine, strike it out."
I think the more esoteric features should be reserved for complex code, especially if it's possible that those features can prove runtime correctness at compile time and result in easily-composable modules. I wouldn't expect more than one or two developers to need to develop such a subsystem, however, so the "clever" is used in isolation.
> No map, no flatMap, no fold, no generics, no inheritance… Do we miss them? Perhaps we did, for about two weeks.
So they weren't complaining about map and flatMap, they just missed them.
Good for them! Their problem domain is likely so simple and neat that it fits the Go's limited built-in types well, and does not lead to frequent copy-paste programming. If so, Scala has been an overkill.
users.filter(_.active).map(_.email)
to be easier to read (and not a pain in the ass to type) than: emails := make([]string, 0)
for _, u := range users {
if u.active {
emails = append(emails, u.email)
}
}
return email
The first style is more explicit about what you want to do, the second style is more explicit about how you want to do it. Go made imperative vogue again, but for me it feels like a throwback all the way to Turbo Pascal. Sure, the Go compiler is really fast, but Turbo Pascal would beat it hands down - on 20Mhz machines with 1MB of RAM.Those dumb Go programmers and their toy programs (https://quicknotes.io/n/1XB0).
There are cases when the restrictions of map() and reduce() are necessary, most famously for a map-reduce in distributed programming, but that's not really relevant for implementing a simple function.
Also, error density is relatively constant per line of code according to most studies (this is a very general statement, but we can assume that most code just isn't trying to be clever). I've forgotten to add(), append() and drop items inside a loop far more than I've made mistakes inside more functional methods.
And, man, tail recursion in a language with function head pattern matching (ML family, Erlang) is so much easier to read than any complicated for loop.
(Update: realized afterwards that "foreach" isn't quite the same as "for", but the larger point still stands, mostly.)
They describe the intent of what to do with the data, not how it is done.
Just like using SQL versus an old xBase database to access data records.
We all know real programmers used gotos.
The very reason those other functional constructs were split out was not due to need, but due to -clarity-. And that same clarity applies to why to use one of those constructs instead of a for-each loop.
Because having three specialized functions for three specialized operations makes it easier to see what a given piece of code is doing. One function per function.
If your brain is organized enough to write clean for loops then ... maybe. But it's a bit opportunity for problems. At least to me; but then I may not be smart enough.
That being said, map and flatmap force immutability in some way. So you pay a price for this, either in speed or in memory, even with tail recursion.
And honestly, sometimes I don't know if code is too "clever" or the reader is just too "dumb".
IMO, the answer is people vastly underestimate the cognitive cost of reading code. "Code" rarely exists in a vacuum, the reader has a universe of inputs, outputs, problems, solutions, failures and goals. The cognitive cost of trying to read someone's code is something that must be paid multiple times per day and at one point do you have to wonder - is the gain in expressiveness for a single programmer worth the cognitive cost of the multiple programmers who have to parse that code.
I'd imagine the answer is no - especially for companies that spend more time iterating and patching based on customer feedback than actually designing and architecting systems. My belief is that expressive languages have their place but companies are far more likely to build their software in a "patch-test-iterate" environment which favors less expressive languages.
Not everyone feels this way, the investment to learn these features may not pay off right away, and if you come from a "move fast and break things" language (python/php/js) it can feel like a waste of time.
Issue is that a beginner pre-conditioned long enough on "verboser, imperativer" models/languages, when reading/comprehending such a codebase, has to literally mentally expand every 1 line into 10 upon reading, for quite a while .. some weeks, some months, as more intuitive grasp sets in slowly over time. Probably what happened at OP's quoted company and with the different speeds in comprehending what "clever" (compact) code some of their coders came up with, what they flippantly called "code that was harder to understand by others"..
Language is important and its expressivness. Babel 17 is must read.
There are two problems with this argument. First, brilliance in code is not a property of what linguistic abstractions the code makes use of, but the elegance of the algorithm and engineering. I sincerely doubt that no brilliant code had been written prior to the introduction of your favorite linguistic abstractions. Second, even supposing you're right, what difference does that make? If your code's maintainers are dumb, do you think that you could change this reality by making life harder for them, or is it your job to adapt yourself to the reality of the system you're a part of? When creating something for dumb people to use, is it a sign of good craftsmanship to make it harder for them to work with?
e.g. https://code.facebook.com/posts/302060973291128/open-sourcin...
This is not an absolute, and needs to be answered in the context of the question: "Does my team work?"
If you ever wonder this, then it's definitely a problem with your code and not the reader. Code that cannot be easily read and understood by others is worthless in any commercial setting.
If, for instance, someone were writing C# and insisted on hand-rolling for loops in all cases[1], because LINQ is "too hard", that's them being lazy and unwilling to invest a tiny amount of effort in learning more effective methods.
[1] There are some cases where it's more performant to use a plain foreach or bare for, but unless you're in tight loops or dealing with ginormous collections, it's a premature optimization.
For instance, python has never had the problems that ruby or perl had.
I never said that. I'm only asserting that no language is completely immune, because hubristic cleverness is intermediate to stupidity and genius.
I think that there are cultural norms and expectations that come with certain languages that make them more or less susceptible to "cleverness."
Cultural norms can indeed help or hurt.
"Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?"
Clever code for the sake of being clever is rarely worthy it.
That said, I do tend to have that mantra a little more present in my head when I'm working with Python.
But given that discipline, scala would outshine go since scala has much better typechecking than go - e.g. http://getquill.io/ can typecheck against a running DB schema, etc.
They don't understand that unclear code is probably the number one cause of technical debt. Nobody wants to waste time trying to understand it so they start to attach workarounds and it just keeps getting worse.
Some of their code is so "clever" that I've refactored the line with 7 method calls just to understand what the hell is going on.
Lambdas and fluent syntax make me quiver with fear. In the wrong hands they let you do unspeakable things
> They don't understand that unclear code is probably the number one cause of technical debt.
At the same time, verbosity can have an obfuscation quality all of its own. For simple assignment, I find a ternary operator very clear and concise, and much preferable to a 5-9 line (depending on style) if/else for a simple assignment. It also might keep you from using the single statement version of if/else if your language supports it, and that's probably justification in itself given how many problems that's caused in the past.
Specifically, I think:
usefulMetric = wantComplexCalc ? complexCalc(foo)
: simpleCalc(foo);
is preferable to: if ( wantComplexCalc ) {
usefulMetric = complexCalc(foo)
} else {
usefulMetric = simpleCalc(foo)
}
even if only because it doesn't obscure intent with what is essentially boilerplate. val usefulMetric = if (wantComplexCalc) {
complexCalc(foo)
} else {
simpleCalc(foo)
} useful_metric = complex_calc(foo) if want_complex_calc else simple_calc(foo) usefulMetric = wantComplexCalc ?
(complexity > 40 ?
superComplexCalc(foo) :
regularComplexCalc(foo)) :
simpleCalc(foo); usefulMetric = wantComplexCalc == false ? simpleCalc(foo)
: complexity <= 40 ? regularComplexCalc(foo)
: /* else */ superComplexCacl(foo)
;I'm not saying that one should go crazy with one-liners or uncommon patterns, but things like ternary operators used with reasonably short expressions in a single line of code are totally valid and should be readable to any average dev out there.
Particularly
> Also keep in mind that you're probably bothering others, more skilful ones, with unnecessarily verbose code which is to them harder to quickly scan through.
I stopped contributing to one Powershell repository because author thought that ps is hard and he wanted Get-Process. I put a "i am the greates babysiter meme" in PR and that was considered very disrespectful
Particulary
> Also keep in mind that you're probably bothering others, more skilful ones, with unnecessarily verbose code which is to them harder to quickly scan through.
Not sure I can think of too many situations where it would be otherwise.
Sounds like it was disrespectful too.
Terse code isn't much faster to read, the difference between a 300 and 400 line file isn't significant.
Your attitude of "he isn't 1337 enough to understand my code" is the logic that leads to no comments and horrible to maintain code in the first place
It doesn't take a lot longer to sit down and understand how ternary operators work, either. C'mon, it's not differential equations, it's just a notation, and a fairly simple one. It might take a newbie slightly more time at first to understand the logic. We've all been there once, you stop and stare at it for 15 minutes, but after a few times of deciphering it you get used to it. It's not about being 1337 (I surely hope that it's not what's considered elite this days), it's about learning new stuff and any averagely intelligent person can do it. Honestly, would you really hire someone who is not capable to (in a reasonable amount of time) teach him/herself how to read a ternary operator? What programming would that person be capable of doing in future?
Smart people can disagree, undoubtedly, but there's a reason why GOTO is considered to be brain cancer and pattern matching is generally considered to be great.
On a lot of those I know what makes code easier for me to read. It's not the same as some of my coworkers. Based on some of your phrasing I suspect we'd agree on a lot of them, fwiw
When the metric used is "easier to read" it becomes far too subjective IMO, things you mentioned are similar but not quite the same
Look at any large C codebase and you will see plenty of goto statements to manage resource cleanup. The problem is using goto in place of structured control flow like loops and if/else. Statements like yours make it seem like there is a conceptual problem with a jump.
https://www.visualstudio.com/en-us/articles/devopsmsft/code-...
Scala provides a whole new level of ability for people to write code that can be meaningless to others.
It really is quite different.
True, but once get into the length of variable names in iOS and Android development, you're in a whole new territory. 38 character variables have no place in life.
And extreme's like:
outputImageProviderFromBufferWithPixelFormat:pixelsWide:pixelsHigh:baseAddress:bytesPerRow:releaseCallback:releaseContext:colorSpace:shouldColorMatch
This is 149 character.