Jump to content

Recent Comments

- - - - -

On C++ Naming Conventions

4: Adsense

I threw myself back into the deep end of C++ again a few months ago, having spent the last couple of years with an emphasis on C# and .NET.

One thing that I'm thinking of is the old subject of coding style. Every software house tends to have a house style, so at work you just adopt that - but at home, on personal projects I find myself drifting around stylistically, at least with naming conventions.

There's a few main styles that I tend to consider ok for me:

.NET Style
Microsoft have a standard set of style guides for .NET / C# programs which for the most part people adopt (although not always, even within Microsoft public code).

The .NET style is simple:
  • PascalCase for class names
  • PascalCase for public methods (all methods, in fact)
  • Interface classes start with an "I"
  • Public properties/variables are PascalCase
  • camelCase for variable names
  • Namespaces are PascalCase
  • Assembly Names are PascalCase
Code would look something like this:
namespace MyProject
    public interface IBar { }

    public class Foo : IBar
        public void DoSomething(int parameterName);
        public int SomeProperty { get; set; }
It's worth noting that the get/set property functions end up becoming something like "SomeProperty_get"/"SomeProperty_set" under the hood.

Java Style

Java programs also have a common style.
  • PascalCase for class names
  • Interface classes start with an "I" (but not always)
  • camellCase for public methods
  • Public properties/variables are camelCase, prefixed with getXX() or setXX() (as Java doesn't have properties)
  • camelCase for variable names
  • Namespaces are lowercase
  • Package Names are lowercase
In Java, the above example looks something like:
package myproject;

public interface IBar { }

public class Foo implements IBar
    public void doSomething(int parameterName);
    public int getSomeProperty();
    public void setSomeProperty(int value);
C Style / C++ Standard Library Style

C++ seems to have a tonne of styles. One of the first ones you'll come across is that of the standard library, which appears to have adopted the C style convention, largely due to remaining consistent with the old code from yesteryear.

Here, we have:
  • lowercase_delimited for class names
  • Interface (abstract) classes aren't special
  • lowercase_delimited for public methods
  • Public properties/variables are lowercase_delimited, there doesn't seem to be a get/set style (?)
  • lowercase_delimitedfor variable names
  • Namespaces are lowercase
Back to our example:
namespace myproject

    class bar 
       virtual ~bar() { }

    class foo : public bar
        void do_something(int parameter_name);
        int get_some_property();
        void set_some_property(int value);
Looking through some other sources and the Google C++ guide seem to lean to a blend of the Java Style with C++/Standard library style.

  • PascalCase for class names
  • Interface classes start with an "I" (but not always)
  • PamellCase for public methods
  • Public properties/variables are lowercase_delimited, prefixed with my_property() or set_my_property()
  • camelCase for variable names
  • Namespaces are lowercase_delimited
This leads to:
namespace my_project
    class Bar 
       virtual ~Bar() { }

    class Foo : public Bar
        void DoSomething(int parameterName);
        int some_property();
        void set_some_property(int value);
With all this, the Google version seems to make a lot of sense.

What's your style and how did you pick it?

Jul 15 2014 05:49 PM

Honestly, I have one simple rule for my own code and for any code I have control over, and that's "Do as the standard library does".


It may not be perfect, but it has two great big benefits -- 1) everyone knows it and can at least read it. 2) Frankly, rather than trying to think about all the corner cases and having to justify your decisions to everyone who disagrees, I can just get all hand-wavey and say "If its good enough for the standard, its good enough for you."


The second part isn't even a lie -- its just such a blunt instrument that the shear weight of it will bludgeon any decentor -- so I don't feel bad about it. At all.


The standard library of any language, essentially out of necessity, exercises all kinds of odd cases your coding standard will miss; its been there, done that, and got the tee shirt. Furthermore, using the same naming convention as the standard forces you to resolve any ambiguous names or collisions explicitly -- sure you might not have had them under a different naming convention, maybe, but I prefer to resolve these kinds of issues now, rather than unknowing leaving them to lie in wait due to a bit of serendipity.


Besides all that, think of the trees you'll save, and CO2 (read: hot air) you'll keep out of the atmosphere by not having to design, share, debate, and defend yet another naming convention. Think of all the braincycles you've spared yourself by deferring to the 100s of man-years of expertise that the standard library designers represent, and all the hours of your life you can have back and use to, you know, write code.

Jul 16 2014 06:39 AM

I'd agree that using non-standard naming conventions for home projects is somehow incoherent, since you'll have to mix it up with coding standards of used libraries anyway. But I wouldn't call debating over that topic a waste of time in general, since it's a productivity related issue. On the other hand, there is a reason that modern languages do not use that lowercase-dashy style. For most of programmers I know camel/pascal case is way much easier to read and maintain, and for some of them it was one of the main reasons to use Java/C# and choose those as professional careers paths over C/C++.
I'd say: you choose your language, obey the rules. The unwritten ones aswell.

Jul 16 2014 09:46 AM

On the other hand, there is a reason that modern languages do not use that lowercase-dashy style. For most of programmers I know camel/pascal case is way much easier to read and maintain, and for some of them it was one of the main reasons to use Java/C# and choose those as professional careers paths over C/C++.


There's no good reason for this, its just a result of the Java-normative world-view that universities are churning out. It was decided some time ago that the standards for CS curriculum ought to be taught in java, and so the schools turn out programmers who believe that Java-style is normal.


If you grow up speaking English, then the subject always comes before the verb. If you grow up speaking Spanish, sometimes the verb comes first. What's 'normal' and reads most-naturally depends on which language you were exposed to.


This conversation is strictly about naming conventions, and if this Java-centric world-view were relegated to that I'd be happy enough to leave people to their weird Java naming conventions. Unfortunately, many more Java-isms come along with the typical modern CS graduate -- They model *everything* as or through classes, they have an over-reliance on garbage collection (often without understanding the performance implications of their usage patterns), and they don't reach for operator overloads when appropriate because Java doesn't have them. Java defines a particular orthodoxy of object-oriented development and, frankly, not a very good one. C# is actually far better from a language perspective, but both are a far cry from Smalltalk or even Simula in embodying a good implementation of the object-oriented paradigm. The situation is bad enough that its nearly impossible to hire a fresh grad who can "think" in C++. They almost don't exist unless they've received specific training, and even then they're not much beyond moderate skill-levels (for example, they mostly wouldn't know about the difference between Generics in Java or C#, and Templates in C++). C++ shops mostly either higher older people, or acquiesce to the fact that they will have to spend the first 6 months beating Java out of their new hires.


I disagree that the shape of your naming convention is a productivity issue -- productivity is gained from having a complete convention and sticking to it -- it has nothing to do with what it looks like unless its aim was to make things deliberately obtuse.


We can agree, though, that your standard should be in keeping with community standards around a particular language. Don't carry your favorite javascript conventions over to your C++ project, or vice versa.

Jul 16 2014 09:50 AM

I follow a style similar to Google's style but slightly different probably due to my C and Java roots.

Namespaces are done in Pascal case.
Class Names are in Pascal case.
Interfaces (abstract) use the I + Pascal case.
Variables are all lowercase separated by _ but typically tend to be short and sweet names.
Functions/Methods are all lowercase separated by _ and again short and sweet.

so you tend to get something like this...


In C++ I typically would not use properties unless the variable is read only or if I need to do some background checking on the data first coming in.  Otherwise I would just expose the variable directly as being public.


namespace MyProject
    class Bar
        virtual ~Bar() {}

    class Foo: public Bar
        void action(int param);
        int data();
        void set_data(int val);
Jul 18 2014 10:55 PM
In my experience, there are very few cases in which interfaces are prefixed with "I" in Java, so I don't think it is the norm there. At least I've seen no such thing in the standard library (nor any other library I've used).
Months ago I started to prefix interfaces with "I" because I thought they were different enough from concrete classes and abstract classes to merit it. After a while I started to think that the whole purpose of interfaces is to keep the user from worrying about the internals. So my conclusion was that prefixing interfaces with "I" is counterproductive to their purpose.
The dedicated prefix singles them out as interfaces and prevents you from intuitively think of it as any other object. Probably there is a reason to single out interfaces when you're coding them or the supporting code around them, but for the user, their usage and "looks" should be indistinguishable from regular classes, or at least that's what I think.
I rely on what I consider less intrusive for distinguishing classes, abstract classes and interfaces by using different colors for them.
EDIT: I see lots of cane shaking here :D
Jul 23 2014 11:45 PM

Personally I don't like the "I" (hungarian notation?) notation, beside my own style rules, I have a big rule:


If something is occurring too often in class names, maybe is time for a new namespace (and that's how is born my Mesh namespace xD. of course there will never be a "I" namespace). That's it, I usually program by interfaces so almost everything in public API should be prefixed with I wich is not good, even in that case I still prefer a " 'Interfaces' namespace" rather than a big "I" in front of the name. Interface is about "how to use" an object, so it doesn't matter if it is pure virtual (IMHO).


Underscored names are in google style guide, but I think the real reason for them is that "_" names are easier to read for search engines (should we optimize our code also for search engines? O.o). I prefer PascalCase for classes, namespaces and functions. and camelCase for methods and member variables (widely adopted convention)


My style is not truly mine, in the mean that I found few girls in my classroom wich was writing really good-lookin code and I tried to figure out how to write it myself (newlines and indentation). I also asked permission for copying that style and immediatly I had a better code :D. Don't invent a style, just find one that you like and use it :D

Jul 24 2014 12:21 AM

One thing that is interesting is that sometimes at the start of a coding project it's not quite clear if you want a pure interface (eg: no data, no method implementations) or an abstract class, which contains some common cruft.


Obviously, you can start with an interface and then base an abstract class on it to be your base class for more specialized implementations, but that does seem to start getting a little nasty.


This case supports the comments about interfaces not starting with "I", so that's an interesting point you guys are making.

Jul 27 2014 05:51 AM

Whether it's an intent to write better code or just a severe case of obsessive compulsive disorder, i think programmers have made a big case of naming convertions just because we've been 'programmed' to always seek for the -best- possible solution. But terrifyningly, i think this subjects falls into one of those dreaded "it's-all-very-subjective" cases.


The way I adapted a naming convension was progressively looking at other people's source code, and one convension rule that they've used i'd like, and another one i'd hate. At one point, I looked at some big guys' source code for conventions myself, but I just didn't like all of em, some felt weird to me.


So through time, I'm now writing code like this:


  • PascalCase for class names
  • camellCase for all methods, properties, variable names
  • Namespaces, Package Names are lowercase
  • Interface classes start with an "I"
  • Abstract classes start with an "A"
  • Enums start with an "E"
  • constant names are all CAPS.
  • private methods, properties, variables, are prefixed with "__"
  • protected methods, properties, variables, are prefixed with "_"
  • function arguments are prefixed with "p_"
  • local variables are prefixed with "l_"
  • brackets take a line on their own and everything inside is indented forward one step


Random copy paste from some source code:

 * Main Display Service Class
 * @author Aris Kostakos
class Display extends AService implements IDisplay
	//@todo: Reflection needed here!!! See above todo
	//@think: this is a nice way to check if a new view/scene/entity/etc has been created.

	public var space( default, null ):IGameEntity;
	protected var _invalidated:Bool;
	public function setSpace(p_gameEntity:IGameEntity):IGameEntity
		//cast the gameEntity, and complain if space already set.
		if (space != null)
			//@note if another space already exists, maybe you can warn better the user, or take
				//other action. may need rerendering, changing renderers, etc, etc, etc
			Console.warn("A space object is already bound to the Display service! Rebounding...");

		space = p_gameEntity;

		return (space);

It works for me so I'm happy...

Note: GameDev.net moderates comments.