Hacker News new | past | comments | ask | show | jobs | submit login
Google C++ Style Guide (googlecode.com)
96 points by olalonde on Feb 20, 2011 | hide | past | favorite | 39 comments



I laughed when I saw this: "If your function crashes upon error, you should append OrDie to the function name.", and then as an example: "OpenFileOrDie". Lol.


I thought it was an old perl convention.

    do_something or die "Somebody set up us the bomb"


What if that was an actual semantic transformation in the language? Naming something XorDie would execute the body of X in a context within which all errors are caught, and if any is found, the call returns NIL or similar?

Easily doable with handler-case, unwind-protect and reader macros, but ugly as sin.


We do the same thing with getX and setX; it would be interesting to see more "meaningful" function names in a language.


This thread is about C++. Therefore, part of this thread must be dedicated to rants about C++. This may be an Internet law.

Thus, here's the C++ Frequently Questioned Answers List:

http://yosefk.com/c++fqa/fqa.html


Oh, C++. I do not like that language.

I have always felt that C++ is a language too complicated in a time where keeping it simple is key. The fact that it needs a style guide that long says it all.


People love to hate on C++, but if your going to, at least hate on things that are actually broken.

For instance every non-trivial language with more than a couple of programmers working with it will have some style (maybe less formal) style guide. Python is often hailed as 'executable sudo-code' yet the community has a style guide, pep8. (Interestingly Google has their own style guide for Python.)

There are plenty of valid reasons to hate on C++, but being a cowboy coder isn't really a valid one.


Pseudo.


Is the open-source Google Python styleguide all that different from PEP 8? It seems basically the same in most of the cases that matter.


Think about it this way: The web browser you are reading this on was likely written using C++. Here's a link explaining why C++ was chosen: http://programmers.stackexchange.com/questions/41883/why-are... Also, 99% of all commercial games for Xbox 360, PS3 and Wii are written in C++ (probably also with some Lua for scripting). Like it or not, C++ is still the dominant language for these domains.


Ok, I know this post is a couple days by now, but if you want to read more the eternal debate that is the C++ programming language, check out this article: http://gigamonkeys.wordpress.com/2009/10/16/coders-c-plus-pl...

There's actually 2 Hacker News posts already linking to this article, so you can read the comments are posted there as well: http://news.ycombinator.com/item?id=885482 http://news.ycombinator.com/item?id=2220917


In order for us to have simple languages they need to be created from low-level ones.

I also think C++ is too complicated, but it's an amazing powerful language, if you master c++ you can pretty much master any language out there.


Obviously we need low level languages. Assembly and C are beautiful languages, even compared to other high level ones. I enjoyed every minute of learning them.

Deep knowledge of C++ is something I would love to have, and I have much respect for those who can grasp all of its concepts.


Regardless of language, that is a fairly terse style guide for a company the size of google. Especially when you consider the scale of their applications.


You should see the size of the style guides for the foundation and steelwork on a sky-scraper!

Of course if you are simply building forts out of sofa cushions then you don't need all this.


Browsing through the rest of the linked SVN, Google seems to have an Emacs mode to help encourage adherence to the style guide:

http://google-styleguide.googlecode.com/svn/trunk/google-c-s...


'Each line of text in your code should be at most 80 characters long. ' We recognize that this rule is controversial, but so much existing code already adheres to it, and we feel that consistency is important.

That's another funny one...


'Existing code' refers to Google's codebase, not necessarily the rest of the world. Then they can do things like have their version control diff apps like Mondrian/Rietveld have fixed-width UIs that fit on one page, when they know that everything will fit within 80 chars.


Also, many Google developers do a big chunk of their development through SSH windows on a laptop working from home. Laptops have limited screen real estate anyway, and it's really handy to be able to use the default PuTTY terminal size and not have to screw around with resizing it.


It also makes life easier if you like to have several code windows open side by side while you work. I got introduced to this approach a few years ago by a colleague and I've loved it ever since (I actually use vertical splits in Vim FWIW; same difference...).


Do they enforce the style guide on VCS checkin? Or is anyone of you enforced to do so?

(FYI: I'm talking about VCS-guards, who prevent checkin's, if they do not comply with a style guide. Maybe someone can run a poll on that topic.)


No, Google requires frequent code review. Coders told me when I visited that code which violates standards or raises any kind of compiler warning needs to be discussed with your team before it's committed and will be identified on review. (or nightly build)

Automated rules built into VCS seemed to be the kind of thing nobody there would tolerate.


Huh, I don't think I've seen this constant naming convention before:

   const int kDaysInAWeek = 7;


It's also used by Apple in all of their Cocoa and CoreFoundation code. An example from CoreFoundation would be their constant CFAllocator references:

    const CFAllocatorRef kCFAllocatorDefault;
    const CFAllocatorRef kCFAllocatorSystemDefault;
    const CFAllocatorRef kCFAllocatorMalloc;
    const CFAllocatorRef kCFAllocatorMallocZone;
    const CFAllocatorRef kCFAllocatorNull;
    const CFAllocatorRef kCFAllocatorUseContext;


We used that C++ constant naming convention at EA, too. I like it because it nicely differentiates C++ typed constants from preprocessor constants and macros (which we SPELLED_THUSLY).


Yeah, it appears it's actually quite common, and I must be one of the last people to be surprised by it. =] I've never been part of a major multi-person C++ project, though, so my stylistic conventions are a mixture of C conventions and the conventions used in the STL. I tend to SPELL_THUSLY even C++ typed constants, though I have also seen them PascalCased (but then, unless context makes it sufficiently clear, they can look like class names).


And useful if the number of days in a week ever changes.


I'm actually learning C and I see it a lot in the book examples regarding macros(#define ....)


Does Google have style guides for other languages? Are any of them public?



I'm curious why everyone who writes style guides seems to hate C++ exceptions.


One thing that I dislike is that it tries to be overly generic, i.e.

   try { throw 5; } catch (const int& val) { printf("%d\n", val); }
   try { throw "hello_world"; } catch (const char *&val) { puts(val); }
I think it would have been much better (and simpler for implementers!) if they had made std::exception a more fundamental part of the language and required that throw be used on a descendant of it. As it stands if you want to be sure to catch any failure from some external code you end up doing:

  try {
    something();
  } catch (const std::exception& ex) {
    fprintf(stderr, "ERROR: %s\n", ex.what());
  } catch (...) {
    fputs("UNKNOWN ERROR\n", stderr);
  }
My personal opinion is that it's easier to deal with C++ exceptions (warts and all) than to try to avoid them. Just about any method that mutates a STL type can have a heap allocation fail and the only reasonable way to report that is via "throw std::bad_alloc();". Just make sure that your code always follows the principals of RAII ( http://en.wikipedia.org/wiki/RAII ) and you'll be fine.


Yes, throwing an arbitrary object as an exception is a humorously ridiculous approach.

It's as if every time a machine broke down in a factory, the workmen would have to wheel the machine into the manager's office, shove it on his desk and shout, "there, there's your problem!"... and if the manager didn't grab the machine, it would fly through his back window...


Well, a couple of reasons. One, as they explained there, C++ exceptions weren't very good when they wrote the bulk of their code. The second reason is that writing exception safe code is hard in C++.

Combining those two, you have code that wasn't written exception defensively having unexpected exit paths due to exceptions and now you've got bugs.

It sounds like they would've included exceptions if they didn't have a legacy codebase. I'm sure that would've added a decent amount to the doc.


Things such as throwing across DLLs, size and time overhead and ABI issues make it not very straight forward to use C++ exceptions on embedded platforms or cross platform software running on several platforms using different tool chains.


For an in-depth discussion on the pros and cons of C++ exception usage, check out this article from the CodeProject: http://www.codeproject.com/KB/cpp/cppexceptionsproetcontra.a.... The Google style guideline simply presents one particular opinion on the usage of exceptions. They figure it's easier to maintain source code (particularly in large open source projects) that only uses error codes, than a mix of error codes and exceptions.

As they say that the end "Use common sense and BE CONSISTENT." http://google-styleguide.googlecode.com/svn/trunk/cppguide.x... If you are modifying a project that uses exceptions, then use exceptions. If you then modify a different project that uses error codes instead, then use error codes. Be consistent above all else.


I wonder, too. I sure agree with them that it's possible to mess up with exceptions, sure, but the alternative -- using error codes is also prone to bugs. For starters:

1) It means that you have to check the return value of every call. Miss one, and errors get ignored, which can result memory corruption or worse.

2) Checking return codes after every function call results in terribly verbose code/ Whereas exception-based error handling, when used in the right way, only needs catch() statements in places where the error is actually handled.

2) Every function has to return a status code. This hijacks the return value, meaning that you cannot simply return a value anymore, you always need to use output parameters.


Click on the triangle next to the guideline; they actually do a good job of justifying most of these rules, including that one.


Yes, their reasons seam to boil down to, "because people often use them incorrectly."




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: