Saturday, October 4, 2008

C++ Coding Standard: Naming Conventions

Now the C++ coding standard takes on the contentious subject of naming conventions. Substitute your own conventions for these if you like, but conventions of some kind can make for more readable code.
  • 10.1. Constant names must be in all caps.
  • 10.2. Private data and function member names must begin with '_'.
  • 10.3. Type names must begin with a capital letter.
  • 10.4. Function macro names must be in all caps.
  • 10.5. Names not covered above must begin with a lower-case letter.
  • 10.6. Do not use underscores and mixed-case in a single name.
  • 10.7. Typedefs must not obscure the fact that a type is a pointer, reference, or array type.
  • 10.8. All class definitions must be within a namespace.
  • 10.9. Do not use negative names that begin with "no" or "not".
All-caps constants are such a common convention that you would be foolish to do otherwise -- remember to make your enum constants all-caps also. I extend the all-caps convention to preprocessor function macros also, because it is often useful to highlight the fact that you're using a macro instead of a real function.

I'm not crazy about Hungarian notation, like tacking a _p onto the end of pointer variables, but you might consider using a _t suffix for type names instead of the leading-capital convention of 10.3, since emacs will colorize the type for you. But only if the resulting names don't break 10.6.

Rule 10.6 only says not to have crazy names like underscore_MixedCase_name; there is no mention of whether to choose underscore_names or mixedCaseNames. You should choose one or the other so that you don't accidentally end up with homophone names like my_var and myVar. If your type names begin with a capital letter, you should probably go mixed-case; if they are denoted with _t, maybe underscore names are for you.

The prohibition on obscuring pointer/reference types is more than a simple stylistic issue. If you typedef Object *ObjectPtr, then const ObjectPtr does not mean const Object *, it means Object * const. The latter -- meaning an unchanging address to a changeable Object -- is of very little practical use. The former -- a pointer to an Object that can't be changed -- is useful both as a way to self-document your code and as a way to let the compiler catch silly mistakes when you try to change something you shouldn't.

Next: function design.

No comments: