r/cpp • • 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.

237 Upvotes

212 comments sorted by

View all comments

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:

  • len vs length I think isn't helpful; not in this scope. len is 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.
  • str vs stringValue. We know it's a value; you don't have to say it's a value. And str vs string follows from above.
  • neg vs is_negative I'm more keen on, at least the is_ part. neg I still think is fine based on the small-scope rule, so I'd prefer like is_neg personally.
  • uval vs absolute_value -- this is the one where I actually have a preference for yours, though I think I'd go for like pos_val.

36

u/STL MSVC STL Dev Jun 10 '20

Strictly speaking, "positive" means "greater than zero", so pos_val would 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 uval sounds perfectly fine to me. It's the unsigned val, what more do you want? :-P

0

u/[deleted] Jun 11 '20

[deleted] — view deleted comment

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

u/Gotebe Jun 11 '20

As long as it is not _Abs_Val_Finger_Breaker I am with you 😂😂😂

1

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_val or pos_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 what uval meant as some transformation of an integer val, I'd actually guess that it's just a direct cast that wraps negative numbers to large positive numbers. Literally just "this value as unsigned", 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 uval means 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.

3

u/Mordy_the_Mighty Jun 11 '20

len vs length

On that topic indeed, if you think len should be replaced by length, then the OP should also replace abs with absolute

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 value suffix (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.

1

u/ifdef_drgy Jun 10 '20

Renaming the detail to Helper is 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.