221 points · by ingve · 6y ago · 217 comments
This is a frequently encountered argument, and sure, if you look at any single line, it looks very obvious what it does. But I would argue that verbosity and lack of abstraction has severe drawbacks for a programmer's ability to understand the overall codebase, and it is disastrous for long term maintainability.
You start out with 20 identical pieces of boilerplate code, and a few years later, you have 20 subtly different pieces of code. Good luck guessing whether the differences were intentional, or accidental. Good luck refactoring the code.
There is no reason simple code can't have higher-level constructs. The interface to them is just likely very domain specific, and you don't start with them.
But after you notice you are copying the same sort of code to a third place, you usually notice a pattern, extract that pattern (with no abstract frills attached) to a unique implementation that can be used everywhere, and move along.
a common pattern I see that leads to this:
1) construct a relatively expensive object. 2) use that object to do A, B, and C (each of which require setting up their own smaller objects)
there are a lot of different places where people want to do A, B, or C, but not necessarily all of them. but people are reluctant to break A, B, C out into their own helper functions because of the cost to construct the object and possibly the very large number of parameters that need to be passed. with enough time/effort, it is possible to detangle this stuff and encapsulate it more sanely, but it's usually easier to just follow the existing pattern.
I want to work where you work.
I've seen literally 4 separate implementations of the same UI component in the last week. It's obvious that they all started out from a common base (e.g. by looking at variable names, function names, etc). However, over time, each component has diverged, as each project that the component was copy-pasted into just made changes willy-nilly to their copy of the component, rather than recognizing that they have a copy of a shared component and refactoring changes upstream or building common abstractions upstream.
Now I've been tasked with doing the refactoring work to make these components DRY, and I can already tell that it's going to be far more work than management has anticipated.
The problem is that every problem is caused by a multitude of causes, and there’s usually no clear way to distinguish issues caused by lack of discipline from issues caused by the wrong coding approach or style.
Different styles make different demands on how disciplined a programmer must be in order to write correct code. My experience in well-managed large code base with decent-size teams is that the recommended approaches and coding styles will evolve to address problems that could be solved by asking programmers to be more disciplined.
So that’s the problem with saying “no coding approach will ever solve an issue caused by lack of discipline”—it only makes sense if you already have a good idea of which issues are caused by a lack of discipline, and if you already understand that, then the saying doesn’t help you. The key insight here is to understand when changing your coding approach may allow you to write correct code with less effort (and discipline). But this can’t be distilled into an aphorism, so it won’t get quoted.
An example is holding a lock to access a certain field. If you’re “disciplined” you can just leave a comment on the field that lock X must be held to access it. But in practice, you want to solve that with code analysis. Another issue is using scoped locks so early returns don’t screw you. You can easily argue that these issues aren’t caused by lack of discipline—but if you travel back in time 20 years or so, “discipline” might be the only tool you have to solve them.
Despite the modern c++ version being the highest quality and the original windows-style version being the most fully featured, the vast majority of people use and prefer the rinky-dink basic c++ version. Simply for the reason that you don’t need to be a senior level dev to contribute meaningfully to the code.
- The official server (arcturus) is awful to work with code-wise. But all the decently big private servers uses it because at one point we only had the binaries of it and it worked out of the box. When the source started to leak too, it was easier to continue forward with that thing.
- The "simple version" which I am assuming you refer to is os(i)rose. This was the only thing you would get BEFORE the official server got leaked. It had some momentum simply for being there since roughly 2006. It was based on Brett19's code which at the time was a 14-something teenager. The same brett that now works on a fully modern C++ codebase that is decafemu.
- The Modern C++ version which if I remember is worked by few folks from osrose came out something like 2 years ago. Passing 2015, the momentum for the game is close to none. So yes, no one will even spin that codebase.
The official server was stolen due to horrible code-practice (C++-wise and software engineering in general), like having plain SQL-injections when creating characters. Worst! This was one of the reason that made the company (TriggerSoft) behind the game go bankrupt. The game was full of security holes back in 2005. This made the game's economy being broken due to few cheaters, created few horrible roll-backs and such. This drained the player's base from the game.
The "simple C++ server" osrose was also plagued by security issues and technical issues. Up to a point that people preferred to patch the official server with dll-injections + assembly rather than trying to make this "simple C++ server" work.
I should also add that Hungarian notation is the prototypical example of dumb, verbose code, that wants to make individual lines easier to understand by dragging type information into every single variable name.
If used wrongly. Joel Spolsky wrote a whole post on it[0], but the TL;DR is that you should use the notation to differentiate between variables of the same type. For example, you might have world coordinates and object coordinates in a game script. Correctly used Hungarian notation would denote them, for example, with `wPosX` and `pPosX`. Even though they're both int (or float), you can easily see that you shouldn't assign one to the other.
Using them to notate types, however, as in `iPosX`, is completely useless. I fully agree with that.
[0] https://www.joelonsoftware.com/2005/05/11/making-wrong-code-...
That is not something you want in modern C++. Quite the opposite, in fact, and many projects avoid Boost for that reason.
Templates should be used when needed, no more.
Not always, though.
See every bug and exploit with C arrays or pointers that exists because C devs think even minimal attempts at safety are too complicated or slow, or old-style PHP code that builds SQL queries out of printf strings directly from POST values, or probably countless other examples in other languages. C++ code that uses raw pointers instead of references or that uses std::vector but never actually bothers to bounds-check anything.
It's entirely possible for code to be too dumb for its own good.
That can also be perceived as a a flaw of the language design in that it does not allow one to write dumb, safe and fast code. Which are such languages in existence today?
edit: fixed typos
- Dumb: you bet. The inclusion of lambdas has shaken things a little, but usually Java code is straightforward with little space for "cleverness". The counterpoint to this, of course, would be the memes about AbstractFactoryFactoryImplementationSubclassDispatcher class names and all that, which IMHO does not represent much actual Java code out there. There are good reasons why big corps prefer Java, and readability is one of them. As a programmer, I've found it easier to jump into a Java codebase I didn't know much about than in any other language. And this has happened even when I had little experience in Java.
- Safe: yes. You have to go out of your way to be unsafe in Java. Memory allocation is done for you and the try-with-resources idiom is almost as good as C++ RAII.
- Fast: also yes. Usually about 2x or 3x the run time of C/C++ code, some times even less.
> The key point here is our programmers are Googlers, they’re not researchers. They’re typically, fairly young, fresh out of school, probably learned Java, maybe learned C or C++, probably learned Python. They’re not capable of understanding a brilliant language but we want to use them to build good software. So, the language that we give them has to be easy for them to understand and easy to adopt.
~ Rob Pike
Zig will be there soon.
I don't know that this is, ipso facto, evidence of anything about C programmers other than that they really hate C++, though.
When is the last time you accidentally mutated a raw pointer? My opinion is that references are just another C++ feature that solves a non-existent problem and has severe disadvantages. And that is non-orthogonality / combinatoric type system explosion. I've seen more than one codebase that consisted to a large degree of adapters for calling the same functionality.
Yes I have seen cases where classes or functions are unnecessarily generic, adding templates when you only needed to support a specific type (YAGNI).
But in the end, most bad code I look at, I completely understand it's syntax. It's the semantics of this so called "dumb" code that prevent me from modifying it or fixing a bug in it for days until I actually understand the rats nest of ideas expressed in the code.
I think using features like using const as much as possible, preferring return by tuple rather than multiple in out parameters and a bunch of other modern C++ features more often than not make code bases simpler than the other way around.
Fix a bug somewhere ... pray to the Nasal Demons you got there before more than two developers duplicated it elsewhere.
I mean, they're only readable to people who have dabbled in variadic templates in their free time. That's how many people on your (future) team?
This line of reasoning is vacously true for any syntax and semantics though. Move semantics and rvalue reference are only readable to people that have taken the time to understand them -- they're undoubtably useful though.
This is the idea behind Golang, isn’t it? That everything should be written out explicitly and not hidden behind abstractions. Some people love that, others hate it.
It's also much easier to avoid allocations to begin with than C# - pointers can be used as interface types without boxing (and taking interior pointers to fields / array elements is allowed), and it's possible to allocate regular Go objects / arrays in unmanaged memory and feed it into any API.
Obviously it's not really designed for it and the ecosystem isn't there but using it hasn't been completely terrible so far.
C++ can be a real bitch and commit one to a mental institution or it can be very helpful if one does not try to play PhD.
I write servers and some other stuff in C++ and find it incredibly easy to use. I just do not do any esoteric things.
Named parameters, for instance. It's insane that function parameters still can't be specified in any order with name=value expressions. That would have saved numerous bugs over the years, but apparently I'm the only one who thinks so. When a language such as C++ is harder to use than Verilog, somebody has screwed up badly.
The thing is what is complex abstraction changes with time. At one time, floating point, especially transcendental functions would have been a complex abstraction. Functions at one time were a complex abstraction. Classes and polymorphism were a complex abstraction. Pointers are a complex abstraction for a lot of people. Linear algebra is a complex abstraction. Transforms are a complex abstraction.
Many times “complex abstraction” just means “an abstraction I am not familiar with”.
Back in the 80’s most games were written in assembler. I am sure many people thought that C was a complex abstraction. I mean, instead of just doing a jmp to a location, now you had a stack and a calling convention and which registers to save and restore...
Since “complex abstraction” is often code for “unfamiliarity”, education, like what the original article is doing is very helpful in moving the state of the art forward. As people become familiar with new abstractions, that becomes the new baseline for “simple” code.
A lot of times it can also mean "an abstraction that my development environment is unaware of or otherwise has deficient tooling for"
Now not all features are bad, lambdas are OK when used as local functions and can make the code more readable if the alternative is to define some static function outside the current method (e.g. you want to pass some custom filter or comparator). They can certainly be abused though, but it is one of those cases where their usefulness is greater than their abuses (and i can't say the same for "auto").
For the example given... it might be a bad example, but honestly i was looking at that code for a bit and i simply cannot read it - i do not understand what is going on just by reading the code, i'd need to run it in a debugger and go through it step by step (and i've actually written texture atlas packers before). It completely fails to sell me on the "fold expressions" and "parameter packs" and it certainly doesn't look at all "elegant" to me (but note that it might be that the example is awful, not the language feature itself).
And it did make me skim through the rest of the article though since after completely failing me on all fronts at the introduction bits, i couldn't get the feel that i have any common grounds with the author.
I mean, sure, if i take that code and run it through a debugger - perhaps while also crossreferencing the features it uses at cppreference.com - then i'd be able to follow it. However at that point any relevance to readability would have been thrown out of the window long ago.
Edit: also the default comma operator discards its lhs, it is pretty much always used for its side effects.
var person = new Person();
var car = selectCarById(carId); // Car
if type is not obvious, it should be explicitly declared.I know i do not use any of the languages you mention, for example - and if i did, i'd explicitly write any type names.
For others, it was worrisome because it made code easier to compile, and rightly so. If it complies it doesn't mean it's correct.
I already wrote that there are some cases where auto is necessary (usually when used with more recent C++ features).
> especially if an IDE is there to expand complex type information
And i also already wrote that this information is not only often cumbersome to obtain but also such an IDE is often not available - e.g. in a web-based code review tool which also happens to be an environment where you want the code to be most understandable.
It's always "ugh, this code is a copypasta convoluted mess. I'm going to replace it with a simple solution".
It's not that different from the English language either. Laying out your thoughts in a clear and structured way is the real skill. Start using words and expressions that I have to constantly google for, and I will hate you very quickly.
You just need to know functional programming.
Know your tools, people.
I always say it as "write code that you could debug at 2:00 am drunk."
Be simple, do not be clever and be clear.
Also, all his code examples are bad. No one would build a texture atlas the way he did for example, and in any practical algorithm one wouldn't be able to use folds like he did. So suddenly one would have to use something entirely else like a for loop or std::accumulate().
It reminds me of the arrogance displayed in the Twitter thread, which is a shame. I think like someone said, experience is valued only by those who have it.
I've been there too though, I was that arrogant young programmer once thinking all these old-timers weren't a match for my technical skills. It usually passes.
Well, that would be a good question to ask to the author, since he titled the article "modern C++ gamedev" and not simply "modern C++" although to me what is discussed seems to be general enough, and "gamedev" here happens to be just the type of project the code comes from... To me, it does not look like he makes any significant contribution on how "modern C++ could serve specifically games development". IMHO he has detected that people in games react strongly to content about C++ and he benefits from the additional exposure he gets by putting "gamedev" in his C++ articles/tweets/anything (which is something I am not judging btw).
Personally, I do think that when your code is simulating a whole parallel universe using a not-super-high-level language, you might end up with challenges regarding readability and flexibility of the raw code that other softwares might not encounter. Not being really part of that industry I feel I can't know for sure, and therefore I have applied the same reasoning to him since he is also not part of that industry, it seems.
I don't think questioning credentials is particularly elucidating here. I don't see any reason the entire thesis of the article is flawed.
As to the throwaway reference to gamedev, the article is in response to shade thrown by gamedevs, attempting to concede specific concerns and propose solutions.
For me the code on the right is far more readable and easier to understand.
- consts are dropped
- variable definitions are merged onto multiple lines
- usefully named constants like `nPixels`, `nBytes` are elided
- the `idx` lambda is inlined
The net effect, for an initial skim, is that the code on the right looks terser and simpler. But in reality many of the "short cuts" hurt the long term quality of the code.Local consts are not particularly useful, especially for things like ints. Compilers know it's const, and a reader doesn't need to worry about it in a local scope.
width, height usually come in pairs, so putting them on the same line is usual.
nPixels and nBytes are not used more than once so they are not useful abstractions, and the pattern of `width * height * bytes_per_pixel` is so common that there is no ambiguity about what it does.
The idx lambda is probably a distracting abstraction which requires the reader to think of it in a different context than the immediate what pixel goes to where. Again, the pixel moving pattern in the right is so common it's familiar to most people working in similar areas, and in terms of error-prone both are not better than the other.
Same thing with doing two separate things in the loop. Not only can it stop the the compiler from optimisations from time to time (the c++ compiler is very clever... but many times it gives up), I've had speed increases in breaking it up into several loops, but I also have to search and in my mind break things up. Very easy to do when I'm writing the code (and I'd probably do the same because of laziness), but quite annoying when I read someone else's code that does it.
I can still assign to it. Sure, you can argue that if the code is complex enough that you might accidentally do that without it being obvious, then the code should be simplified or split up, but that's besides the point. If its const, the compiler will complain, if its not, it will silently let me. Nobody can write ideally-factored code all of the time and following good consistent practices helps. Also, I hear arguments like that all the time, but so much of actual real-world shipped code breaks these "rules", so I'd rather be pragmatic and choose a style that improves otherwise imperfect code.
Its also as much a hint to future me that the variable is intended to not be modified.
> In my particular scenario, all the texture file paths are hardcoded
That feels like a very unique case. Usually data is given in a vector or something and then you're out of luck anyways. Plus the syntax is very unintuitive (think about your colleagues), debuggability is zero.
Also the argument about constness feels a bit contrived. Sure with this you can write const and feel good, but the other version is hardly a bad nonconst. You can wrap things in functions or whatnot. The function seems to be a bit long anyways.
Parameter packs can make some ugly code substantially simpler, IMHO. For example, I contributed some changes to the Godot C++ bindings a couple of years ago that made a number of super common functions variadic instead of having to create and pass in collections (eg debug printing, specifying argument types when registering signals, stuff like that). While not a strictly necessary change, it makes the resulting code easier to read. Parameter packs allow this.
[1] https://en.cppreference.com/w/cpp/container/vector/emplace_b...
edit: This also shows that you don't have to be able to write variadic templates to reap the benefits of it. You can enjoy the benefits while using a library that uses it.
Hopefully modules will allow mixed optimization levels for template headers.
Metaprogramming also lacks a good debugging story, but I would be happy to be proven wrong.
In my opinion these are not language problems, but tooling problems.
I get the sense the author's deliberately stirring controversy.
Separately, I think programming itself is solitary and predisposed to people who don't focus on building social skills (myself included). I think online (pseudonymous) communication can introduce all sorts of problems.
[1] https://www.youtube.com/playlist?list=PLTEcWGdSiQenl4YRPvSqW...
> This function attempts to allocate a temporary buffer equal in size to the sequence to be sorted. If the allocation fails, the less efficient algorithm is chosen.
Or is this not what you consider a "functional construct"?
But the C++ versions of these take the result location as an argument. It makes chaining them together a hassle because you have to create all the intermediate containers explicitly.
I think there are good reasons for the STL to work this way, but it can make programming in a functional style pretty inconvenient compared to a lot of other languages.
See e.g. here: https://github.com/ericniebler/range-v3/tree/master/example
Then he wrote a blog post on it.
I got burnt so many times by runtime craziness already that the only thing I want happening at runtime is trivial code running from top to bottom.
But if you enjoy runtime hacks, more power to you! You must be a much better developer than me.
I’ve been using C++ for about 15 years now, and also tbh, and dislike just about everything beyond 11-14. The cognitive load reading code has just skyrocketed. The simple basis of the issue was when the meaning of existing syntax elements being “overloaded”. &, &&, [] in my mind. It is not complicated or profound reasoning - simple as now you need to decipher more context to understand what is being expressed. I’ve been materially disappointed to spend 5-10 minutes reading a small bit of unfamiliar code only to learn that what it ultimately expressed was truly trivial. It just makes you feel like c++ has become like the toxic parts of academics/math where everything is expressed in the most complex way possible to establish superiority over others.
The comments about debug ability are true. STL sources/template stacks are absolutely terrible to work with. Luckily with the STL though, what 99%+ of the time, the bug is in your usage, so it doesn’t matter much. To be fair though that is a trade off - I feel like I’m on vacation debugging c# or Python, but that is (almost) an intrinsic benefit of interpreted languages, with the well-known associated costs. Just templates... the cognitive load of having to understand (simply read) and debug code from an abstract definition introduces significant pain in terms of debug ability and general usability.
“C++ is not the STL” - true but c’mon - whatever is built-in mostly defines the stuff that you can be sure is portable, and rely on as a standard practice/resource in large projects. Very few sane people want 5 different implementations of a vector or string from god knows where with god knows what bugs. In the industry for c++, there is serious need for the _option_ to “reinvent the wheel” of standard libs, but it shouldn’t be that this is necessary to achieve baseline performance or usability in common use cases.
I am of the same opinion as at least one other below - simplicity of implementation and readability of language are king in the “real” world. What’s better than the beauty of a meta-programmed, absolute masterpiece of modern C++ and zero-cost abstractions? A program that I can understand in 10 minutes two years after it was written, or better yet that can be understood and debugged by 90% of skill levels instead of 10%.
This conversation could, and does, go on without end. My net-net conclusion so far is that modern C++ has done more harm to itself than good because it is trying to be too much. When the creator of the language can’t even keep up with it enough to call himself an expert, it’s a pretty obvious red flag that things have gone off the rails.
The other day I explored std::promise and std::future, only to realise that all it is under the hood is a semaphore (which starts with count of zero) and a pointer. The promise.set() updates the pointed memory and releases the semaphore, while future.get() waits for the semaphore and reads the memory. My workaround was just as many lines of code with abstractions that are no more complex. So whats the point of promise/futures? Async adds spawning a thread to the mix, yet another unneeded abstraction. Coroutine adds more. Just be done with this and add proper Actor model and call it a day.
And having just one loop makes it simpler too.