For those of you who name you member variables with no special notation like m_foo
or foo_
, how do you name parameters to your ctors and setters?
I tend to follow the first letter of the parameter that is being set, and disambiguate with this...
void setFoo(int f) { foo = f; }
For a simple setter, for one variable, it is pretty well clear.
Also, I often do this
int setFoo(const int f) { foo = f; }
so I can string things together.
I always do this:
Obj(int foo) : foo(foo) {}
I used to play games with appending funny symbols until one time I got hit by this:
Obj(Bar& b) : b_(b_) {}
Can you see the mistake? (Yes, b_ is a private member reference variable). It compiled without a warning. Cost me 3 days of debugging (I was a green programmer then).
Now I always use the same name to avoid typos (and subsequent crashes) like that. There is no ambiguity inside the initialization list. This part of the language was designed just for this case, so take advantage of it.
I always go for a Param or Arg suffix but only when disambiguation is necessary.
Obj(int fooArg) : foo(fooArg)
I avoid (by avoid mean never use) underscore as the first character of any identifier. I know its overkill but worth the effort.
Read this: What are the rules about using an underscore in a C++ identifier?
Though not a rule I limit the use of underscore and prefer camel case to make my variables readable. But that's just a personal preference and I don't mind reading code that uses it.
Additionally I never name parameters the same as my member variables. The compiler will not help you catch the kind of errors this can generate (and this is all about getting the compiler to do the real work so you can do the expressive work the compiler can't do).
int X::setWork(int work)
{
this->work = work; // OK. But more Java like.
work = work; // Compiler won't see that problem.
}
int X::setWork(int newWork)
{
work = newWork; // A bit harder to get wrong.
}
I name the actual members with trailing underscores, so I do this:
Foo(int bar) : bar_(bar) { }
The reason is so I can use getter functions without anything like getBar() (bar() is better).
I used to follow the Microsoft convention of prefixing member variables with m_
, like m_foo
. At my current company the convention is a trailing underscore for member variables: foo_
.
Generally, if you are working by yourself, then use whatever convention you like. If you are working in a team, use whatever the team agrees upon. Overall consistency in a code base is what is important, not the particular convention.