r/cpp • u/ifdef_drgy • Jun 10 '20
Why is std implementation so damn ugly?
Recently I remembered a moment from my uni years when immediately after handing in the assignment of implementing our own string data structure we were warned not to ever try to implement and use our own data structures. Which is exactly what you want to hear after working hours on such assignment. However the reason behind it makes sense, you would be only reinventing the wheel and let's be honest, it will be also way slower than data structures in the almighty std library. Now think about it, what kind of black magic is behind the std's speed? Well I had no idea so I took a peak, lets see the code:
inline string
secret_function(int __val)
{
const bool __neg = __val < 0;
const unsigned __uval = __neg ? (unsigned)~__val + 1u : __val;
const auto __len = __detail::__to_chars_len(__uval);
string __str(__neg + __len, '-');
__detail::__to_chars_10_impl(&__str[__neg], __len, __uval);
return __str;
}Hey, I bet you just skipped the whole code part. I know it looks unreadable, but please try to go through it and guess which std function it might be (obviously its not called secret_function, but i'm pretty sure you used this function at some point).
It's only 6 line function but it took me a while to figure out what each line does and I believe this could be fixed very easily just by naming the variables and functions with a bit more descriptive names. Just to prove the point here is an example of how I would structure this function:
inline string secretFunction(int value) {
const bool isNegative = value < 0;
const unsigned absoluteValue = Helper::abs(value);
const auto length = Helper::charCount(absoluteValue);
string stringValue(isNegative + length, '-');
Helper::insertIntAsChars(&stringValue[isNegative], length, absoluteValue, 10);
return stringValue;
}While the functionality stays exactly the same, I think this chunk of code is much more pleasant to read and it's pretty obvious what the code is doing on each line. From this you should have a solid guess which function it is (you can leave a comment), but the real question is why would anyone write such code? Especially when nowadays everyone is talking about how code readability is so important. Is this how they wrote code back when std was released and they didn't bother to change it? Or am I just too inexperienced that I couldn't figure it out immediately?
EDIT: Thanks for the insightful comments, for anyone reading this the reason variables are beginning with __ is macros. If user defines isNegative macro, it will get overwritten in the std, however user is forbidden to define macros starting with __ , as the wise people of reddit comment section suggested. However underscores aren't the only issue with this code, the main issue is I think using short non-descriptive names of variables/functions which is very confusing in functions that are doing more complicated operations.
40
u/evaned Jun 10 '20 edited Jun 10 '20
Let's look at each of the changes you made.
First, the underscores. As discussed by others, this is basically non-negotiable and is needed to avoid conflict with valid user code.
Second, you've got some renames; I'll start with detail vs Helper. A detail or details namespace is a pretty strong C++ idiom, so this rename isn't really helpful. Edit: just to be clear, I don't think your name is worse taken in isolation, but I also don't think it's better, and there are lots of "details" namespaces that are used for implementation details.
Third, you rename to_chars_len to char_count and to_chars_10_impl to insert_int_as_chars (aligning style to snake case). While at some level your names are "nicer", they lose information. The first loses the fact that the char count is based around what to_chars will produce. What if there are other ways of formatting an int? Which one does char_count/charCount produce? insert_int_as_chars not only loses the fact that this is special to to_chars but also loses the fact that it's formatting in base 10. Edit: Ah, after seeing another comment I see you pass the base as a parameter. As that comment said, you may have just killed performance of that function.
Fourth are variable renames:
lenvslengthI think isn't helpful; not in this scope.lenis a very common and natural abbreviation for lenth. I think this even though I am much more resistant to abbreviations than most programmers, but remember that this is a six-line function. You don't need to look around for the definition. A common rule that I like -- the bigger the scope the more important it is to be explicit and clear. But the reverse is also true -- not only does a smaller scope let you use a more abbreviated name, but I kinda think in many cases you should.strvsstringValue. We know it's a value; you don't have to say it's a value. Andstrvsstringfollows from above.negvsis_negativeI'm more keen on, at least theis_part.negI still think is fine based on the small-scope rule, so I'd prefer likeis_negpersonally.uvalvsabsolute_value-- this is the one where I actually have a preference for yours, though I think I'd go for likepos_val.
36
u/STL MSVC STL Dev Jun 10 '20
Strictly speaking, "positive" means "greater than zero", so
pos_valwould be a misnomer.10
u/daedalususedperl Jun 11 '20
So then
abs_val?24
u/STL MSVC STL Dev Jun 11 '20
My brain has been irradiated by Standard Library rays for 13 years. I can no longer think like a user, and
uvalsounds perfectly fine to me. It's the unsigned val, what more do you want? :-P1
u/evaned Jun 11 '20
uval sounds perfectly fine to me. It's the unsigned val, what more do you want?
FWIW, the reason I'm a little with OP on this one and kind of prefer something more like
abs_valorpos_val(despite your correct criticism of that one, I still think it's my favorite :-); "abs_val" to me is too suggestive of the function rather than the result, but maybe that's just me) is that if you asked me in a vaccuum whatuvalmeant as some transformation of an integerval, I'd actually guess that it's just a direct cast that wraps negative numbers to large positive numbers. Literally just "this value asunsigned", as a separate variable for some combination of explicitness and ease of use.That being said, it's hard to pick perfect names and so there's always some tradeoffs, if you've got convention in a code base for what
uvalmeans that can make up for a lot even if newcomers would have to learn that convention. So don't interpret this too far down the "they should have done such and such!" path.0
Jun 11 '20
[deleted]
11
u/STL MSVC STL Dev Jun 11 '20
Yeah, I can't really argue against
abs_val. Or_Abs_val, as the people of my planet would say.1
3
u/Mordy_the_Mighty Jun 11 '20
lenvslengthOn that topic indeed, if you think
lenshould be replaced bylength, then the OP should also replaceabswithabsolute1
u/ifdef_drgy Jun 10 '20
Renaming the
detailtoHelperis my inexperience with std i guess, however this change is not particularly important and renaming it to Helper wouldn't do much.Would be passing the base as a parameter into inline function such a big performance hit? stoi/stol/stou has this for example.
Using long names in most of the variables is redundant in this case as you pointed out, however there are multiple variables/functions which have shortened names but its unclear what are they actually doing until you read their implementation, so in this case it was more about consistency than anything else.
7
u/thedictatorofmrun Jun 10 '20
Stoi etc take the base as an argument because it is totally reasonable to expect that a caller of that function may not know what the base is supposed to be until runtime, but there's pretty much no question that stoi_base_10 would be faster at least in some cases.
1
u/m-in Jun 11 '20
I agree with your assessment. All those perceived problems are borne out of inexperience. Lots of this is almost idiomatic. Some of the verbosity is silly like the
valuesuffix (what else could it be?!). It’s just like inexperienced programmers comment code; they just reiterate the obvious: what the code does. Because that’s their problem level: they are so focused on the elementary that they think just getting the code to do what they want is a big obstacle. Whereas what comments are really for is explaining the bigger picture - what the code does in context of what it’s used for, and the purpose of it all. That stuff is beyond what beginner programming students can easily deal with. They aren’t there yet, and the sort of “improvements” OP made are rather indicative of it.
18
u/serviscope_minor Jun 10 '20
So the __ thing is because of macros I believe. For example the user could have:
#define isNegative somewhere before they #include the header and that would cause it to break. Double underscored symbols are reserved by the compiler, so you're not allowed to use them or rather the compiler is allowed to break if you do.
-5
u/ifdef_drgy Jun 10 '20
That doesn't seem right, I'm looking at multiple files and the macros are starting either with
_or__, also as far as I know it's good practice to have caps lock on when you are naming your macros, which would avoid these collisions.6
u/1-05457 Jun 10 '20
Unless you're talking about more standard library implementation files, the macros shouldn't start with double underscore.
And not everyone uses all caps for macros.
1
u/ifdef_drgy Jun 10 '20
Yes I was talking about multiple std files, that I have currently opened
13
u/1-05457 Jun 10 '20
Those are part of the compiler implementation, that's what the double underscore names are reserved for.
-3
u/neutronicus Jun 10 '20
In practice I think if you are writing some open-source, header-only data structure library, you should probably name things with
__as well, for the same reasons?Doing so pushes some maintenance responsibility onto you (because compilers might break your names at any time), while making your library less brittle in the face of users with arbitrary standards-compliant macro names.
9
u/1-05457 Jun 10 '20
Any compiler, including some obscure one for some microcontroller or something.
You'd be better off picking a "namespace" to prefix macros with (and using an actual namespace for everything else).
2
u/neutronicus Jun 10 '20
and using an actual namespace for everything else
This doesn't stop user macros from clobbering your names though, right? So any name in a Header is vulnerable?
4
u/1-05457 Jun 10 '20
No, though that's why external headers should be included at the top of a file, before any user defined macros.
If you really want resilience to these problems, use separate compilation as much as possible, keeping the contents of the header to a minimum. Though that's not really possible for data structures.
4
u/trvlng_ging Jun 11 '20
No. All identifiers containing __ are reserved to the implementation through all time and all versions. No user library, including open source libraries should use it anywhere in any name. If an implementation breaks your library, that is on you.
48
u/neutronicus Jun 10 '20
I'm looking at multiple files and the macros are starting either with
_or__If you're looking at Standard Library files, that's the point. They're allowed (by the Standard) to name Macros that way, and no one else is. So they name all their Macros that way to avoid trampling (or being trampled by) user Macros.
So if you start a macro with
__in your own code and the Standard Library explodes, the Standard says it's your fault, not the Standard Library implementors'.18
u/Wenir Jun 10 '20
Literally 4 days ago someone posted a library with macro "Ok" https://www.reddit.com/r/cpp/comments/gxn1bn/i_reimplemented_rusts_result_type_in_c_using/ft31yv3
12
u/o11c int main = 12828721; Jun 10 '20
I once broke several dozen Gentoo packages because zlib defined
ONandOF, and making that hygienic revealed that so many people copy-paste libraries into their source trees in an unclean manner.7
u/OldWolf2 Jun 10 '20
I'm having a problem at the moment because a library does
typedef unsigned char BOOLin its headers, and another library doestypedef int BOOLin its headers. This version can't be fixed by temporarily#undef-ing things either.Thunks, here we come
10
u/o11c int main = 12828721; Jun 10 '20
The fix is:
#define BOOL header1_BOOL #include "evil_header1.h" #undef BOOL #define BOOL header2_BOOL #include "evil_header2.h" #undef BOOL17
u/anydalch Jun 10 '20
"good practice" isn't always followed, and the standard library is supposed to be robust in the face of any c++-compliant code, no matter how ugly. if your code defines a macro named
isNegative, it's probably bad code, but it's still valid, and the compiler has to accept it and compile it right. if your code defines a macro named__neg, it is ill-formed, because that name is reserved.11
u/foonathan Jun 10 '20
The standard library has to work with every user code in existence. I don't want my isNegative macro to break code.
So they have to use names reserved for the implementation, like _Uppercase or __anything.
7
u/serviscope_minor Jun 10 '20
So, the compiler is allowed to do what it likes: the compiler writers know which macros starting with __ they use and can make sure they don't use any that break their library code. As a user though you're "not allowed" to make your own macros starting with __ and so the compiler writers can assume you won't. In other words, if you do use a macro with __ and compilation breaks it's your fault and you need to fix your code rather than them needing to fix theirs.
I know it's good practice to have caps lock on when you are naming your macros, which would avoid these collisions.
Absolutely 100% true. Unfortunately the compiler has to work with code that uses all of the worst possible practices provided it sticks to the letter of the standard.
2
u/m-in Jun 11 '20 edited Jun 11 '20
Listen, how many lines of C++ have you written? Because this is going into a territory where you are grasping at straws with somewhat elementary stuff that anyone with 3 years of solid industry experience with good mentors would have a firm grasp of. So I guess I question your judgment here: why do you expect core library code to be written like learning material? It’s almost never possible. And the level of complexity of the code you chose is really low I’d say. It’s in the category of reasonably easy stuff to read, even if it is not very easy to write it right the first 5-10 times.
If you cared to ask me: code that’s hard to get correct but reads much easier is what we all strive for. You completely, but yes - completely and utterly mischaracterize what’s going on here. You’re losing the sight of the forest for individual trees, nay - for the bark peeling on that birch over there. I’m serious now, it’s getting pretty absurd the deeper you go.
What you see as problematic is all in all very nice code, and the problems you see are not where the real problems are. STL has problems but they haven’t got anything to do with mundane stuff like that. They have to do with a much much bigger picture that takes a decade to sort of become visible, and another decade to become clear. I speak from my own experience here - there are more focused and skilled people that may get to the zen level in 12-15 years, if they really push themselves or half that if they are very very top notch.
3
u/bohan Nov 15 '20 edited Nov 15 '20
With C++20 modules, this way of writing code is going to become totally obsolete, thanks to macros being out of the way (no more ugly underscores) and comments not being a compilation cost anymore (interfaces compiled just once unlike headers). We'll someday enjoy an auto-documented standard library from within the IDE code completion, like some other programming ecosystems have been able to provide for more than two decades.
1
u/ifdef_drgy Nov 15 '20
Thanks for commenting, I will look into the macros of c++20, didn't read much about those, but I was mainly talking about how the implementation looks, imho the documentation is actually pretty good on the web, just the code doesn't look appealing.
2
17
u/BenFrantzDale Jun 10 '20
Tangent: will C++20 modules mean we don’t have leaky macros and so the standard library (at least the module version) not have to be uglified by underscores?
14
u/redditsoaddicting Jun 11 '20 edited Jun 11 '20
As far as I know, yes, preprocessor definitions won't interfere anymore. There's still all sorts of unintuitive stuff that a module-based standard library has to do (
::std::v1::blah—rather_STD blah,++it, void(), ++it2,std::addressof, etc.), but without macro interference, it would be free to use normal names.detailcan also go away if you want by treating all unexported names asdetail::, though I suspect there will be debates over that.However, I don't expect to see any major implementation change to meet this until perhaps new modules come that don't have any header equivalent. For all the existing library, the old way still has to be supported because the vendors care about that.
3
Jun 11 '20
[removed] — view removed comment
2
u/BenFrantzDale Jun 11 '20
Good point. Now I see why the standard says double underscore is UB: between macros and this stuff, lord knows what could happen. It still feels like the compiler should be able to know when user code uses double underscore and make it a compile error.
34
u/BrangdonJ Jun 10 '20
I don't think Helper is much better than detail. The point of detail is that it's implementation detail and not something users should use. A helper could help users too.
I don't have much problem with to_chars_len and to_chars_10_impl, either, except that for consistency it should be to_chars_10_len. The idea is that one function tells you how much space you need so you can allocate it, and the other fills it. The function names should be closely related because their functions are so related. I think insertIntAsChars is a bad name for something that appends.
(The macros thing is addressed by others.)
15
u/_Js_Kc_ Jun 10 '20
I think insertIntAsChars is a bad name for something that appends.
The to_string implementation seems to preallocate the whole string (filled with minuses), and then __to_chars_10_impl gets passed the memory range (presumably to write the base10 representation in place).
It neither inserts nor appends, it overwrites.
7
u/muungwana Jun 10 '20
Part of the reason has to do with trying not to collide with user defined macros.
4
u/Revolutionalredstone Jun 11 '20 edited Jun 11 '20
At some point (after about a decade of daily c++ programming) you become completely comfortable at reading code irrespective of symbols / whitespacing, at that point density alone (scrolling) becomes the new key bottleneck, all of my more recent code is totally uncomfortable to read for newbies but extremely fast to read / modify for pros.
I think its a natural progression but it does definitely cause problems, i for one started by becoming tired of simple classes requiring 5 pages so i started in-lining single-line functions, then short functions, and now i basically crunch code to the point that it just barely can be be viewed using a widescreen monitor...
When i'm writing brand new code or trying to debug complex control paths i will expand that area, but generaly all my code now looks like something from std::vector. Right or Wrong, that's my perspective, happy coding!
4
u/m-in Jun 11 '20
I’m with you on that. The stuff I write is easy for anyone with at least 5-7 years of C++ experience to grok, but it’s absurdly hard for most interns. Experience counts for something, people. Don’t lose sight of that.
10
4
u/ezoe Jun 11 '20 edited Jun 11 '20
I do hope STL implementation use better self explanatory identifiers rather than the cryptic short identifiers. I mean, come on, this is 2020. we don't have insane linker limitation where symbol length including the name mangling must be less than a 16 bytes. The modern C++ implementation supports the identifier length of hundreds if not thousands characters. We deserve to have a better longer identifiers.
For people here who are arguing usual bikeshedding like helper vs details. You're missing the point. Do you really think, neg, uval, or len are more readable than the longer names? Other than the very famous name like i for index counter variable name, these name should at least be a full English word(negative, unsigned_value, or length) than a short fist three letters of the original word.
People have some opinions for helper function vs manual inline which I don't care much.
The double underscores for the identifiers is necessary for safety. Because most STL are header files.
The user can overwrite non double underscore identifiers by macro before including the STL header files. The identifiers that includes double underscore are reserved for the C++ implementation. If the user overwrite that, it's their problem.
1
u/RevRagnarok Jun 11 '20
We deserve to have a better longer identifiers.
/u/m-in noted a very good reason.
11
Jun 11 '20 edited Jun 11 '20
Look at Java's standard library OR the JVM implementations. Look at C#.Net's standard library. Look at Swift's standard library.. Objective-C's standard library. Now compare them to C++s'.. yeah..
C++'s standard library LOOKS like absolute trash compared to the others. Even decompiled Java code via fernflower looks better..
It's not just the usage of ___ There are literally variable names like:
__x, __i, __p* __p1* __p2* __c* __last* __m* I was extremely surprised the first time I opened up the `<algorithm>` header.. When I came to the realization that there is nothing about it that makes these functions that make them more performant as its just variable names and syntax difference.. I came to the understand that this is just done on purpose and there is no good reason or explanation for it. Even when C++ modules come out and stuff can belong to the std, there will still be people defending the use of this unreadable code.
My favourite one is (from <cmath>):
template <typename _Fp>
constexpr
_Fp __meh(_Fp __a, _Fp __b, _Fp __t) noexcept {
if ((__a <= 0 && __b >= 0) || (__a >= 0 && __b <= 0))
return __t * __b + (1 - __t) * __a;
if (__t == 1) return __b;
const _Fp __x = __a + __t * (__b - __a);
if (__t > 1 == __b > __a)
return __b < __x ? __x : __b;
else
return __x < __b ? __x : __b;
}Without seeing the function name, you might as well start reverse engineering the function to see wtf is going on.. There is not a man on the planet that can defend the fact that this could be written with proper variable names and syntax and still have the exact same performance but with better readability.
The function is actually: __lerp.. I have seen worse though.. especially when templates and iterators are involved.
4
u/m-in Jun 11 '20
Those variable names you point out are very typical, and usually are used in certain ways and it’s hardly confusing. Remove the underscores and look at the code then. Lerp is a primitive. If you don’t know what it does by sight then understanding it is no easier with longer variable names. What little background I have in visual perception would tend to steer me towards shorter variable names in complex expressions, since our fovea has only so many degrees it can cover. Once the names get too long, it’s impossible to clearly see the structure of the expression anymore.
4
u/Nobody_1707 Jun 11 '20
The only real problem with that Lerp are the underscores, and those are still necessary because this is in a header file and macros are global.
1
Jul 21 '20
It's not needed at all. The variables are local to the function so by lookup, it would find it first.
1
u/Nobody_1707 Jul 21 '20
The preprocessor doesn't understand scope. It simply sees the macro and replaces it with its definition.
6
Jun 11 '20 edited Jun 11 '20
[removed] — view removed comment
1
Jul 21 '20
I would just remove the underscores (which aren't needed since they variables are local to the function) and give them names:
v0, v1, time.orv0, v1, interval.
3
u/_Js_Kc_ Jun 10 '20
Why the hell is that "unsigned absolute value" not a standard function?
At least as of C++20, that hack there is actually guaranteed to work, but how would you have done it in a conforming way in prior standards (in user code)?
4
u/m-in Jun 11 '20
You didn’t. You leveraged documented platform-defined behavior. To do otherwise is called, well, myopia. Losing sight of the forest for the trees. Making up imaginary problems. That’s how I see it. Let it rest. Just let it rest already.
2
u/_Js_Kc_ Jun 11 '20
To do otherwise is called, well, myopia. Losing sight of the forest for the trees. Making up imaginary problems.
The opposite would be a cognitive deficit in abstract reasoning, then?
If the standard does not allow something to be implemented in a way that does not depend on platform-specific behavior, or makes it needlessly cumbersome, that's a deficiency in the standard. Because that's the whole point of having a standard in the first place. To standardize things across implementations.
It's a valid point of criticism, it's a valid question to ask, and it's a valid issue to discuss. It doesn't preclude reaching for the platform-specific solution in practice to get shit done.
2
u/Wetmelon Jun 11 '20
Sorry what’s the question? It’s basic twos complement math, it should be guaranteed to work on any twos complement based system
3
u/_Js_Kc_ Jun 11 '20
it should be guaranteed to work on any twos complement based system
Which wasn't guaranteed until C++20. How would you have implemented this prior to C++20 in user code?
But even with guaranteed two's complement arithmetic, it should be a standard library function. I'd even argue that
std::absshould have returned an unsigned type from the beginning.1
u/wyrn Jun 11 '20
At least as of C++20, that hack there is actually guaranteed to work, but how would you have done it in a conforming way in prior standards (in user code)?
const unsigned uval = neg ? (unsigned)-val : val;That said, I agree that
uabsprobably should be a std function. Lots of other obvious things are missing from cmath though, I suspect to maintain compatibility with C.3
u/_Js_Kc_ Jun 11 '20
Isn't that UB?
-valis signed arithmetic that overflows (ifval == INT_MIN).I thought that was the reason the to_string implementation used the explicit one's complement plus one for negation.
1
u/wyrn Jun 11 '20
You're right, it's UB. I'm not sure about that being the reason for the two's complement expression though, since the same argument that allowed the implementer to write it before c++20 would also apply.
2
u/_Js_Kc_ Jun 11 '20
Can't be sure, but what could be the reason then? Just to look fancy? This makes perfect sense as an implementation for a compiler that treats signed overflow as UB and also has two's complement signed integers. Otherwise it would need a compiler intrinsic or a hack in the compiler to exempt the stdlib from the overflow UB.
Edit: About the C compatibility: cmath already has C++-only stuff such as float overloads of abs (without the f prefix). Adding stuff wouldn't hurt compat, especially if kept only in std::.
1
u/wyrn Jun 11 '20
As far as I understand it, signed is overflow is UB so compilers can implement obvious optimizations like
x + 1 > x->true. I don't see what optimization opportunity is there by simply negating the value; if anything if I were writing the compiler I'd use the opportunity to just use the neg instruction or something similar which does the right thing. I'm not saying you're wrong, it does seem like the most likely explanation; all I'm saying is that, if there's something in gcc's entrails which would support the two's complement expression over the naive negation, I can't imagine what it would be. Perhaps you have a better imagination than I do?Edit: About the C compatibility: cmath already has C++-only stuff such as float overloads of abs (without the f prefix).
Yeah but those are just overloads, which future C standards are unlikely to add, so in that sense they're inherently safe from collision with any possible evolution of C's
math.h. If you were to add anstd::uabs, and then a future C standard adds auabswhich did something else, you'd have the annoying inconsistency thatstd::uabsanduabsdo different things. I don't know for a fact that that is the reason why obvious quality of life things likesgndon't get added tocmath, but again I can't imagine another reason for it.2
u/_Js_Kc_ Jun 11 '20 edited Jun 11 '20
Well, one obvious optimization in the same vein would be
std::abs(x) >= 0->true. Also, it was just a hunch on my part, but it's the only reason I can think of (and it's a fairly straightforward explanation).The name clash is of course a possibility, but that applies to absolutely everything, not just
cmath. You could simply call itstd::unsigned_absolute_value. C would never add such a readable name.Besides,
absandstd::absalready do different things, even today.abs(-3.5f) == 3,std::abs(-3.5f) == 3.5f. Yeah, because they're overloads. But the point is, it does different things depending on if you prepend std:: or not. uabs wouldn't be worse.Edit: Added a minus sign. Not that it matters, but it was intended.
3
u/Beetny Jun 11 '20 edited Jun 11 '20
I've always wondered if the STL could have the best of both worlds by maintaining their code without underscores and having the shipped code be the output of an "obfuscation" preprocess step. Of course i'm expecting that the nature of C++ grammar makes it impossible.
10
u/Plorkyeran Jun 11 '20
It would not be particularly difficult to write a tool which did that transform, but in practice the people working on the library implementations get used to the code style and stop caring. It's only a problem for people not used to it, and those people will be looking at the obfuscated version so you haven't gained anything.
3
Jun 11 '20
However underscores aren't the only issue with this code, the main issue is I think using short non-descriptive names of variables/functions which is very confusing in functions that are doing more complicated operations.
That differs between standard library implementations. _ILikeMyReallyLongNamesThankYouVeryMuch.
5
Jun 11 '20
not to argue the whole of STL is readable but this block of code is absolutely readable and this is coming from a person who rarely reads STL (but enjoys how it intensifies that an expert wrote the code). (It is okay if you couldn't spot two's complement).
compiler programmers know how to make their codebase best maintainable and this includes the fact that they follow good naming conventions for their purpose as others also mentioned.
verbose variable names dont necessarily improve the code. on the contrary they make the code more bloated in my opinion. so it's a trade-off between readability and purpose-communicability. something like neg doesn't need to be is_negative or len length. uval compliments val and the function name's have references to other related functions.
2
u/jmnel Jun 11 '20
Yeah honestly the underscores just make my eyes want to look away, but I understand why they are there.
On the other hand I really like the outward facing side of std and try to match its style in my code.
2
u/serg06 Jun 11 '20
we were warned not to ever try to implement and use our own data structures
What if you need one that isn't part of STL?...
2
u/Full-Spectral Jun 11 '20
That's a pleasant poem compared to some parts of the STL. Try some of the crazily templatized bits.
2
Jun 11 '20
As a personal preference, I find camel case harder to read than even the original implementation
3
u/trypto Jun 11 '20
I totally agree with you. I would just say that the stl is not meant to be an example of good coding style or good practice. The lack of comments is also glaring but I bet the excuse is compile time or file size or something else.
If you want to nitpick further, why use ~ plus one instead of simply negation like -val? To be clever?
Also fishy is using a boolean value to index into a string. I get that this implicitly converts to integer 1, but it won’t fly in other languages. Again trying to be too clever.
4
3
u/wyrn Jun 11 '20
If you want to nitpick further, why use ~ plus one instead of simply negation like -val? To be clever?
Clang and gcc both generate the same code for either version, but MSVC does not: https://godbolt.org/z/qbDY9M
That said, it's hard to imagine these 5 lines of assembly arithmetic being the bottleneck in a function that allocates space for a string, and it's even harder to imagine that the version with a jump is better than the one without (in a case like this where the input may as well be of either sign), so beyond noticing the difference I got nothing.
1
u/trypto Jun 11 '20
So it’s an optimization? Seems questionable as you said.
But the point is there are no comments explaining why. If you weren’t familiar with twos complement math then you’d be confused. Not to mention the lack of parenthesis around the expression.
3
u/m-in Jun 11 '20
I don’t look much at STL but that stuff really doesn’t need comments. Really. If you need comments for that, I’m worried about what other code bases might prove impenetrable to you. Given what it does, and how well documented its semantics are. Cppreference is an integral part of every STL implementation in practice - they just don’t bother copy pasting it all in there. It’s much better to have it open in a separate window.
All I see here is lots of inexperienced people with very limited perspective. STL implementations are far from perfect, but as far as any code goes their ratio of readability to write ability is absurdly good. They are very hard to implement and comparably trivial to read. This ratio is literally an inverse of the one in STL for most software out there - most code is very hard to read and put in a bigger picture even though it’s comparably easy to write, and very often similarly easy to write better at a local scale (I.e. more idiomatically and with less low-level pessimization).
4
1
Jun 11 '20
You have the same namingConvention for types, functions and variables. var_iables are not like TypesAndFunctions which is why I find your version highly confusing.
1
u/die_liebe Jun 18 '20 edited Jun 18 '20
> he main issue is I think using short non-descriptive names of variables/functions which is very confusing in functions that are doing more complicated operations.
I always thought that, because STL is scanned and parsed zigmillons of times, all whitespace is removed (including comments), and variable names are made a short as possible. It is for efficient compilation.
I suppose that they have a tool for it, and somebody, somewhere has a readable version.
And one more point: STL as you find it, is not source code. It only looks like source code, because C++ compilers do not have an obj format for template code. If STL would be a usual library, it would in an .obj file, and you wouldn't even be able to look at it.
1
u/NilacTheGrim Jun 23 '20
I don't find the original function hard to read at all.
Note that they must use all those __ chars to deal with possible C macros on some platforms.
-1
-1
u/o11c int main = 12828721; Jun 10 '20
Some more reasons:
EBO is a hack
no way to branch based on whether code is valid, without overloading
1
u/staletic Jun 11 '20
You forgot "compressed" pairs and tuples, that allow smart pointers with empty deleter types to be just as big as a raw pointer. In other words, wrap your deleters in a non-capturing lambda if you can.
1
0
Jun 10 '20
[deleted]
2
u/ifdef_drgy Jun 10 '20
Thanks, that explains quite a bit and I'm aware that "pretty code" is highly subjective matter, however most of the std's code looks bad from objective perspective I believe. This was just very simple example in which you can probably guess what __neg variable is. However they are shortening the names of variables everywhere and many places it's quite ambiguous, so I think giving it a full name is better, but with isNegative variable it was more about consistency than anything else.
3
u/advester Jun 10 '20
Honestly, I have thought in passing that the implementers are trying to obfuscate their code to keep us from digging into it and becoming dependent on some inner detail.
9
u/thedictatorofmrun Jun 10 '20
i doubt this is the explicit intent, but i definitely think they are not spending much, if any, time thinking about how legible their code is to non-experts, which in practice results in the same thing
4
u/m-in Jun 11 '20
That code is not meant to be read by non-experts. I’m totally serious here. It’s an implementation detail. The fact that you can read it at all is a quirk of the language. Normally it’s simply not visible. You don’t get to read C# or Java standard library on the daily - not without decompilers that only relatively recently became standard in IDEs. Once C++ gets modules you won’t be having access to the implementation by default. Problem solved.
0
u/twirky Jun 10 '20
That's actually funny and not without sense. It's really tempting to dog through STL code but it's also not a good idea to learn from it how to write code.
0
Jun 10 '20
[deleted]
5
u/m-in Jun 11 '20 edited Jun 11 '20
Oh come on. You’re deluded if you think that TeX is some shining example. It does what it does well, but the design of its language is an utter turd. It only “does it well” if you twist yourself into its confines. A lot of its shortcoming are just poor design decisions that were not rectified because the author would rather make the code perfect at the cost of usability sucking oodles. It’s a truly beautiful and bug free turd written by a dude who can focus like few other people can. The sort of work only someone like Knuth could do. Doesn’t make it any less of a turd. TeX is horrible. That sort of focus is absolutely indispensable in works like TAOCP, but at what cost? You can barely talk with Knuth, I’m serious. Listening to him lecture is miserable. His is the sort of mind that seems tailored for encyclopedic output, but not software design and not everyday communications either.
Such approach in a software project usually results in highly polished and perfected designs that absolutely suck. If anything, TeX is an example of what not to do, and turning the code base into a book only meant it was much harder to revise it or make changes to the code since now you were editing a book with code thrown in rather than just code. Ugh. It sounds good on paper, but it’s nothing to be proud of when done to a software project with any hope of growth and maintainability. It sure is nice for example code and in teaching to document short programs. For anything else it’s an iron ball on a chain.
1
170
u/thedictatorofmrun Jun 10 '20
There is a lot to unpack here, so this might be a bit long.
Another comment has already touched on the reasoning behind the leading underscores being to avoid collisions with macros.
You seem to make the assumption that the standard library is extremely fast, moreso than anything a mere mortal could write. This is wrong. The standard library does have pretty good performance but for specialized applications it is definitely possible to beat it, and for simple things like vector/array/string it is not difficult to match it. The strength of the standard library is that it is performant enough for the vast majority of applications, that it is designed to be very generic, and that it is, well, standard.
Additionally, readability is extremely important for most applications and libraries but the standard library isn't really one of them. You're not really meant to read or edit the standard library unless you are an expert, so readability is kind of a secondary concern.
Your translation of this function to be more "readable", incidentally, is actually probably less performant than the standard library version because (1) you are calling a separate function for abs rather than doing the twos complement inline and (2) you added a "base" argument to the "to chars" helper method which in the original version is known at compile time. Maybe you get lucky and it compiles down to the same thing, but in my opinion it looks like it'll probably be somewhat slower.
I will say that you probably are a little inexperienced with the style of programming that the STL uses, and with more experience looking at these definitions it will probably not be too hard to see what is happening in these functions. The only tricky thing I see here is the twos complement absolute value thing, and the rest of the confusion is probably just the naming conventions being unfamiliar.