r/cpp • u/Shidell • Jun 19 '23
I'd like to adopt a modern style using snake_case, and was looking for opinions.
I'm a Windows (win32) dev and I think snake_case is a lot easier to read. I'm considering switching, but I'm not totally sure about some things:
The stdlib is using all-lowercase for types; I like the idea for fields and properties, and I think I like it for methods, but I kinda want types to be a little more concrete. One suggestion is upper-case the first letter of the first word, e.g. "Foo_bar". Of course, the problem I have with this, is that the std lib isn't doing it—which makes me second-guess it.
Enums: Are enums foo_bar, Foo_bar, or FOO_BAR? I think I like the idea of immutable values being SCREAMING_SNAKE_CASE, so statics, macros, and enums would be FOO_BAR::FOO, for example.
Any thoughts from people who've switched? I'm tired of seeing a mix of Pascal and Camel case, with Hungarian Notation thrown in. Even Microsoft's switched (when I tried looking for their style guide), but I couldn't find a 'modern' style guide replacing it.
7
u/be-sc Jun 19 '23
Go for it. After working with lots of different styles I think snake case is the most readable, too. Although that’s purely a personal feeling.
C++ allows using case and spelling to distinguish different kinds of things. Why not use those tools? I suggest you keep it simple, though. Case/spelling doesn’t have any inherent intuitive meaning. Too much nuance will be lost on a lot of readers of your code.
In my own code I use case/spelling to mark important categories of things in the language. In a nutshell:
PascalCase for types (because types are really important in C++)
ALL_CAPS for macros (dangerous, so a reader should always be aware that a macro is involved)
snake_case for everything else
Regarding enums: Be careful with the terminology. enum is short for enumeration. That’s the type you declare with the enum keyword. The members of such a type are called enumerators.
I like the idea of immutable values being SCREAMING_SNAKE_CASE
Why? What’s so special about an immutable value that it needs to stand out? It’s apparent from the value’s type. It’s a completely normal thing spread throughout the whole code. Being const is about the most mundane thing possible. If you really think immutability is worthy of grabbing the readers attention, then shouldn’t you also do:
void do_something(const std::string& INPUT_STRING)
{
const bool IS_LONG_ENOUGH = INPUT_STRING.size() >= 42;
// ...
}Imo this is beyond ugly! All caps does stand out massively, but is also really hard to read in larger quantities.
I agree for macros. Those are dangerous, and that’s the reason to make them stand out.
1
u/Shidell Jun 19 '23
You're right, and that's a great example. I think my issue is just letting go of old habits, mostly, and some struggle in doing so.
5
u/ohdog Jun 19 '23
Mixing capital letters and underscores in the same name always seems weird to me, except in the case of all caps for macros. Pascal case for type names and snake case for everything else. This is the way.
Of course in the end you can do what you want.
4
u/Full-Spectral Jun 21 '23 edited Jun 26 '23
Not to use the R-word again, but it was both disgusting and a big relief moving to Rust, with its well defined style. It was VERY different from mine, and at first I hated it. But, once I got used to it, I'm fine and the fact that almost everyone is going to use that style since the compiler whines if you don't, is a huge benefit to readability.
C++ could clearly introduce something similar. Optional of necessity, but anyone could enable it and ensure all their code meets that style guideline. Over time more folks would use it and/or convert to it.
The great advantage to these defined styles is that it just nips in the bud a huge amount of religious warfare and the time wasted thereon. It can just be declared, we use the defined style, end o' story. If you don't like it, leave. No one feels like someone else's (clearly degenerate) style won over theirs.
The same of course with a standard formatting scheme, which Rust also has. You just apply the formatter and be done with it. Over time, everyone knows what that format is and just writes that way to begin with. And most anyone coming on board is going to know that format already since it's the default one.
Having written a very large C++ personal code base, I really get the advantage of completely consistent style and format throughout. And it's hard to get there once it's more than one person, without basically having it automatically applied and/or enforced.
→ More replies (1)
10
u/gracicot Jun 19 '23 edited Jun 19 '23
SCREAMING_SNAKE_CASE should be reserved for macros only, full stop. Nothing else should have this naming style. No enums, no global constant, no constant static class data member. ONLY macros. Just use normal snake case for constants and enums.
→ More replies (1)
1
u/1syGreenGOO Jun 19 '23
I'm tired of seeing a mix of Pascal and Camel case
I think that the reason you are seeing this is that google recommends this in their style guide.
I too follow google style guide in my personal projects. A lot of open source libraries follow these too:
https://google.github.io/styleguide/cppguide.html
They use CamelCase for types and snake_case for variables and class members. Enum options are also camelCase starting with letter 'k': kFooBar, kBarFoo
Of course, the problem I have with this, is that the std lib isn't doing it—which makes me second-guess it.
There is also notion about that in abovementioned style guide:
If you are naming something that is analogous to an existing C or C++ entity then you can follow the existing naming convention scheme
2
u/Shidell Jun 19 '23
Google's guide is partially why I wanted to ask this in the community, because I don't really like some of that—CamelCase and Hungarian Notation stuff.
I will admit, though, that old habits die hard. I'm really tempted to prefix a raw pointer with p, for example, or "p_", in this case.
→ More replies (1)
1
u/fdwr fdwr@github 🔍 Jun 19 '23
with Hungarian Notation thrown in
Hmm, at least as far back as 2007, the Windows API design guidelines clearly said "Do not use Hungarian notation". So any occurrences you're seeing must be older API's, like gdi32 and kernel32 that already had that precedent.
Even Microsoft's switched
Note WinRT is a weird mix, the strange kid on the block adopted from Kenny Kerr. Barring those template helpers, I don't believe actual core Windows APIs have "switched". e.g. To pick a random recent example, it's LearningModelBinding::HasKey(), not LearningModelBinding::has_key(). (anyone with counterexamples is welcome to comment below)
I think snake_case is a lot easier to read
Do you see variables like "block index" more as compound words (e.g. doghouse, cheesecake, snowball) or more as individual words in a sentence? Reading studies have shown that reading individual words is indeed faster with underscores that visually chop up the words, but that correctly understanding the holistic logic of the code is more accurate when words are not so visually chopped up, because then you see the variable names as just compound identifiers that participate with nearby operators. 🤔⚖ Some of these studies even used noncoders for their reading experiments and purported that because noncoders could read individual words faster that therefore professional coders could understand snake_case code better 🙃. That's like saying that because a professional car racer understands how to use a car-like steering wheel better than a joystick that professional helicopter pilots should use steering wheels instead of joysticks 🤣. (I'm not meaning to imply you are a beginner by that, but more criticizing some of the study conclusions as standing on flimsy logic)
Personally, I found after working in a PascalCase::camelCase codebase for many years and then working on Chromium and ONNX Runtime with PascalCase::snake_case for the past few years, that going back to PascalCase::camelCase just reads more smoothly like silk and feels much more aesthetic overall when looking at equations. 🤷♂️ For me, the more that code looks like confetti (a variety of NAMING_and_CasingStyles_jammedtogether in the same codebase), the more it slows me down to read and write it. Granted, different libraries (std, Qt, your app...) will have differing conventions, and that's fine, but within a given domain (your app code, stdlib code, Qt code), it's really nice for them to be internally consistent and less confetti, because whichever your preference, logical consistency is elegant - form identifier names with underscores consistently or form them with casing consistently, but not a chimera hybrid like class_name::MethodName() 😋.
3
u/Shidell Jun 20 '23
Unfortunately, a huge amount of Microsoft's Windows libraries are old, and were written when Hungarian Notation was part of their style. When I work with it now, I try to preserve that style—but I've been thinking about snake_case, and moving away from it.
There are some examples that I still kinda want to hold on to, like p for a pointer, but others, like lpsz, or dw? I'm ready to move on. I guess in that vein, I'd continue to use h (HANDLE.)
When I said Microsoft had switched, what I meant is that they no longer embrace Hungarian Notation, etc., and don't suggest following the older styles—but unfortunately, Microsoft hasn't published (publically, at least, to my knowledge) a 'modern' C++ style guide. If they did, I'd probably try to adhere to it, as we're a Microsoft shop.
I appreciate the note regarding conducted studies, and I take your point. Between C++ and C#, as a Microsoft shop, I'm accustomed to PascalCase/camelCase, and I can see (and agree with) you regarding readability. I think the revelation for me when considering snake_case was two part: First, although I'm used to Pascal/camel case, upon refactoring some existing code, it did seem easier to look at—I felt like it was less difficult for my brain to decode the text on the screen, it "felt" better. The other was similarly named fields and methods, for example:
GetIndexA(); GetIndexB(); GetCurrentPositionA(); GetCurrentPositionB();Which became:
get_index_a(); get_index_b(); get_current_position_a(); get_current_position_b();The second (to me) felt easier to parse and was also easier to interpret when scanning quickly (e.g. using IntelliSense.)
I haven't really put this into practice yet; I just started considering it yesterday, and felt ambiguous about certain things (like types being all lowercase as well, which feels strange to me right now), and wanting to use all caps for enumerations, which is really just a product of Win32 flags also being all caps, and feeling like I want to follow that convention, too, even though I'm intentionally trying to move away from it.
2
u/PoorAnalysis Jun 25 '23 edited Jun 25 '23
I feel you, I also prefer snake_case and use it for all my platform independent stuff. Tho I do like the convention of using PascalCase for generic types, so I follow that too. But I work mostly with Windows APIs and sometimes feel like I should declare a variable in camelCase if it's a Win32/RT type. It's especially bad if I'm c&p-ing code from MSDN, do I rewrite it?
My solution: don't stress over it, I stick with snake_case for everything unrelated to Windows, and don't care if the code that interacts with the Windows API is an inconsistent mess.
That goes hand in hand with the randomness with which I fully qualify WinRT types vs usings. So in that sense I'm consistently inconsistent.
1
u/pdp10gumby Jun 19 '23
I use lower_case except for PREPROCESSOR_MACROS (which I don't write myself anyway, so when use one I'm refering to an existing symbol).
You can't pronounce case so it seems weird and even dangerous (you could silently define foo and Foo which would definitely would be a bad thing to do, even (especially) on purpose.
1
u/Zulauf_LunarG Jun 19 '23
If you're contributing to another project (at work or online) use their style guide.
If you're creating your own project, pick what you like, but use something like clang_format to make sure you stick to it.
If you're creating a project to collaborate on, shop around the various existing styleguides out there and pick one. No styleguide is perfect, and any you invent won't either, and by reusing an established one, you can just point to it, and avoid arguments on the team about the minutia that people always hyperventilate about. Add a pre-checkin hook, or CI check to ensure it is used by all contributors (some people go all passive aggressive about style).
1
u/CornedBee Jun 20 '23
We use Upper_snake_case for types at work. It was a bit weird at first, but you get used to it. Standard types not using it is just background noise.
For enum values, we have no consistency at all, some are SCREAMING_SNAKE, some are normal_snake, some are Capitalized_snake. Well, we are consistent in that a single enum doesn't mix styles ;-)
1
1
u/vickoza Jun 21 '23
I prefer Pascal and Camel case. I use snake case when I want to design thing for the standard library for consistency. SCREAMING_SNAKE_CASE are best use for macros as that has been the historical case. I this snake case should be all lower case as capitalization is trying to bring back some versions of Pascal and Camel case. Names should tell what the object/type/variable does with the possible exception of types that do common task like indexing through any container with random access or or storing data into a temporary variable.
24
u/tjientavara HikoWorks developer Jun 19 '23
I use snake_case in my own library. Using the style from stdlib.
Everything is snake_case, including variables, types, enums, constants, globals, function-like-macros (stdlib uses lower-case macros for function-like macros like
assert()).The only thing that is CamelCase are template arguments, like stdlib.
The only thing that is SCREAMING_SNAKE_CASE are
#defineconstants that are used for architecture identification.