C++ Coding Standards: Naming Standardization - Online Article

Standardization is Important

It helps if the standard annoys everyone in some way so everyone feels they are on the same playing field. The proposal here has evolved over many projects, many companies, and literally a total of many weeks spent arguing. It is no particular person's style and is certainly open to local amendments.

Good Points

Then a project tries to adhere to common standards a few good things happen:

  • Programmers can go into any code and figure out what's going on.
  • New people can get up to speed quickly.
  • People new to C++ are spared the need to develop a personal style and defend it to the death.
  • People new to C++ are spared making the same mistakes over and over again.
  • People make fewer mistakes in consistent environments.
  • Programmers have a common enemy :-)

Bad Points

Now the bad:

  • The standard is usually stupid because it was made by someone who doesn't understand C++.
  • The standard is usually stupid because it's not what I do.
  • Standards reduce creativity.
  • Standards are unnecessary as long as people are consistent.
  • Standards enforce too much structure.
  • People ignore standards anyway.
  • Standards can be used as a reason for NIH (not invented here) because the new/borrowed code won't follow the standard.

Discussion

The experience of many projects leads to the conclusion that using coding standards makes the project go smoother. Are standards necessary for success? Of course not. But they help, and we need all the help we can get! Be honest, most arguments against a particular standard come from the ego. Few decisions in a reasonable standard really can be said to be technically deficient, just matters of taste. So be flexible, control the ego a bit, and remember any project is fundamentally a team effort.

Standards Enforcement

First, any serious concerns about the standard should be brought up and worked out within the group. Maybe the standard is not quite appropriate for your situation. It may have overlooked important issues or maybe someone in power vehemently disagrees with certain issues :-)

In any case, once finalized hopefully people will play the adult and understand that this standard is reasonable, and has been found reasonable by many other programmers, and therefore is worthy of being followed even with personal reservations.

Failing willing cooperation it can be made a requirement that this standard must be followed to pass a code inspection.

Failing that the only solution is a massive tickling party on the offending party.

Accepting an Idea

  1. It's impossible.
  2. Maybe it's possible, but it's weak and uninteresting.
  3. It is true and I told you so.
  4. I thought of it first.
  5. How could it be otherwise.

If you come to objects with a negative preconception please keep an open mind. You may still conclude objects are bunk, but there's a road you must follow to accept something different. Allow yourself to travel it for a while.

6 Phases of a Project

  1. Enthusiasm
  2. Disillusionment
  3. Panic
  4. A Search for the Guilty
  5. The Punishment of the Innocent
  6. Praise and Honor for the Non-Participants

Flow Chart for Project Decision Making

                       +---------+
| START |
+---------+
|
V
YES +------------+ NO
+---------------| DOES THE |---------------+
| | DAMN THING | |
V | WORK? | V
+------------+ +------------+ +--------------+ NO
| DON'T FUCK | | DID YOU FUCK |-----+
| WITH IT | | WITH IT? | |
+------------+ +--------------+ |
| | |
| | YES |
| V |
| +------+ +-------------+ +---------------+ |
| | HIDE | NO | DOES ANYONE |<------| YOU DUMB SHIT! | |
| | IT |<----| KNOW? | +---------------+ |
| +------+ +-------------+ |
| | | |
| | V |
| | +-------------+ +-------------+ |
| | | YOU POOR | YES | WILL YOU | |
| | | BASTARD |<------| CATCH HELL? |<-----+
| | +-------------+ +-------------+
| | | |
| | | | NO
| | V V
| V +-------------+ +------------+
+-------------->| STOP |<------| SHIT CAN IT |
+-------------+ +------------+


Leadership

I wish i had said this, but it was said by asd@asd.com in comp.software-eng.

Leaders:

  1. lead by example
  2. don't ask anything of anyone they wouldn't do themselves
  3. are called on to make difficult and unpopular decisions
  4. keep the team focused
  5. reward/support their team in whatever they do
  6. keep/clear unnecessary crap out of the way of the team

Consensus is great. If it lasts for the project lifecycle, consider yourself blessed. I've been on a couple projects where two engineers just blantantly disagreed!They were always:

Programmer #1 says " x = 1"
Programmer #2 says " x != 1"

That's when a Project Leader is required. Unless you want to flip a coin.

Oh yah - one more thing. Project leaders: TAKE the blame when things go wrong and SHARE the credit when things go right.

Ain't easy - but it's the way I try to run my life.

Resources- Take a Look!

General

Book Recommendations

What are some good C++ books you can buy for you and your team?

  1. Koenig/Moo's "Accelerated C++"
  2. Lippman/Moo's "C++ Primer" 4th Edition
  3. Bruce Eckel's "Thinking In C++"
  4. Scott Meyers "Effective C++"
  5. Dewhurst's "C++ Gotchas"
  6. Meyers' "Effective STL"
  7. Josuttis' "The C++ Standard Library"
  8. Vandevoorde/Josuttis' "C++ Templates"
  9. Langer/Kreft's "Standard C++ IOStreams and Locales"
  10. Sutter's "Exceptional C++"
  11. Sutter's "More Exceptional C++ and Exceptional C++ Style"
  12. Martin's "Agile Software Development: Principles, Patterns, and Practices"

Names

Make Names Fit

Names are the heart of programming. In the past people believed knowing someone's true name gave them magical power over that person. If you can think up the true name for something, you give yourself and the people coming after power over the code. Don't laugh!

A name is the result of a long deep thought process about the ecology it lives in. Only a programmer who understands the system as a whole can create a name that "fits" with the system. If the name is appropriate everything fits together naturally, relationships are clear, meaning is derivable,and reasoning from common human expectations works as expected

If you find all your names could be Thing and DoIt then you should probably revisit your design.

Class Names

  • Name the class after what it is. If you can't think of what it is that is a clue you have not thought through the design well enough.
  • Compound names of over three words are a clue your design may be confusing various entities in your system. Revisit your design. Try a CRC card session to see if your objects have more responsibilities than they should.
  • Avoid the temptation of bringing the name of the class a class derives from into the derived class's name. A class should stand on its own. It doesn't matter what it derives from.
  • Suffixes are sometimes helpful. For example, if your system uses agents then naming something DownloadAgent conveys real information.

Method and Function Names

  • Usually every method and function performs an action, so the name should make clear what it does: CheckForErrors() instead of ErrorCheck(), DumpDataToFile() instead of DataFile(). This will also make functions and data objects more distinguishable.

    Classes are often nouns. By making function names verbs and following other naming conventions programs can be read more naturally.

  • Suffixes are sometimes useful:
    • Max - to mean the maximum value something can have.
    • Cnt - the current count of a running count variable.
    • Key - key value.

    For example: RetryMax to mean the maximum number of retries, RetryCnt to mean the current retry count.

  • Prefixes are sometimes useful:
    • Is - to ask a question about something. Whenever someone sees Is they will know it's a question.
    • Get - get a value.
    • Set - set a value.

    For example: IsHitRetryLimit.

    Include Units in Names

    If a variable represents time, weight, or some other unit then include the unit in the name so developers can more easily spot problems. For example:

    uint32 mTimeoutMsecs;
    uint32 mMyWeightLbs;

    Better yet is to make a variable into a class so bad conversions can be caught.

    No All Upper Case Abbreviations

    • When confronted with a situation where you could use an all upper case abbreviation instead use an initial upper case letter followed by all lower case letters. No matter what.
    Justification
    • People seem to have very different intuitions when making names containing abbreviations. It's best to settle on one strategy so the names are absolutely predictable.

      Take for example NetworkABCKey. Notice how the C from ABC and K from key are confused. Some people don't mind this and others just hate it so you'll find different policies in different code so you never know what to call something.

    Example

    class FluidOz             // NOT FluidOZ
    class NetworkAbcKey // NOT NetworkABCKey

    Class Names

    • Use upper case letters as word separators, lower case for the rest of a word
    • First character in a name is upper case
    • No underbars ('_')
    Justification
    • Of all the different naming strategies many people found this one the best compromise.

    Example

       class NameOneTwo

    class Name

    Class Library Names

    • Now that name spaces are becoming more widely implemented, name spaces should be used to prevent class name conflicts among libraries from different vendors and groups.
    • When not using name spaces, it's common to prevent class name clashes by prefixing class names with a unique string. Two characters is sufficient, but a longer length is fine.

    Example

    John Johnson's complete data structure library could use JJas a prefix, so classes would be:

       class JjLinkList
    {
    }

    Method Names

    • Use the same rule as for class names.

    Justification

    • Of all the different naming strategies many people found this one the best compromise.

    Example

       class NameOneTwo
    {
    public:
    int DoIt();
    void HandleError();
    }

    Class Attribute Names

    • Attribute names should be prepended with the character 'm'.
    • After the 'm' use the same rules as for class names.
    • 'm' always precedes other name modifiers like 'p' for pointer.

    Justification

    • Prepending 'm' prevents any conflict with method names. Often your methods and attribute names will be similar, especially for accessors.

    Example

       class NameOneTwo
    {
    public:
    int VarAbc();
    int ErrorNumber();
    private:
    int mVarAbc;
    int mErrorNumber;
    String* mpName;
    }

    Method Argument Names

    • The first character should be lower case.
    • All word beginnings after the first letter should be upper case as with class names.

    Justification

    • You can always tell which variables are passed in variables.
    • You can use names similar to class names without conflicting with class names.

    Example

       class NameOneTwo
    {
    public:
    int StartYourEngines(
    Engine& rSomeEngine,
    Engine& rAnotherEngine);
    }

    Variable Names on the Stack

    • use all lower case letters
    • use '_' as the word separator.

    Justification

    • With this approach the scope of the variable is clear in the code.
    • Now all variables look different and are identifiable in the code.

    Example

       int
    NameOneTwo::HandleError(int errorNumber)
    {
    int error= OsErr();
    Time time_of_error;
    ErrorProcessor error_processor;
    Time* p_out_of_time= 0;
    }

    The standard pointer notation is not entirely satisfactory because it doesn't look quite right, but it is consistent.

    How do you handle statics? There's never a reason to have a static local to a function so there's no reason to invent a syntax for it. But like for most absolute rules, there is an exception, that is when making singletons. Use a "s_" prefix in this case. Take a look at Singleton Pattern for more details.

    Pointer Variables

    • pointers should be prepended by a 'p' in most cases
    • place the * close to the pointer type not the variable name

    Justification

    • The idea is that the difference between a pointer, object, and a reference to an object is important for understanding the code, especially in C++ where -> can be overloaded, and casting and copy semantics are important.
    • Pointers really are a change of type so the * belongs near the type. One reservation with this policy relates to declaring multiple variables with the same type on the same line. In C++ the pointer modifier only applies to the closest variable, not all of them, which can be very confusing, especially for newbies. You want to have one declaration per line anyway so you can document each variable.

    Example

      String* pName= new String;

    String* pName, name, address; // note, only pName is a pointer.

About the Author:

No further information.




Comments

No comment yet. Be the first to post a comment.