C++ Coding Standard.pdf

C++ Coding Standard.pdf - C Coding Standard C Coding...

Info icon This preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 6/11/2015 C++ Coding Standard C++ Coding Standard Last Modified: 2008­03­01 [email protected] / Using this Standard. If you want to make a local copy of this standard and use it as your own you are perfectly free to do so. That's why I made it! If you find any errors or make any improvements please email me the changes so I can merge them in. I also have a programming blog at that is accidently interesting at times, as is my wiki at . Contents To make comments on this page please see the new Disqus comment section. Pferor was also nice enough to make a copy of this document available in pdf format. 1. Introduction Standardization is Important Standards Enforcement Accepting an Idea 6 Phases of a Project (joke) Flow Chart of Project Decision Making (joke) On Leadership 2. Resources­ Take a Look! General Book Recommendations 3. Names Make Names Fit Include Units in Names No All Upper Case Abbreviations Class Names Class Library Names Method Names Class Attribute Names Method Argument Names Variable Names on the Stack Pointer Variables Reference Variables and Functions Returning References Global Variables Global Constants Static Variables Type Names Enum Names #define and Macro Names C Function Names C++ File Extensions 4. Documentation Comments Should Tell a Story Document Decisions Use Extractable Headers 1/86 6/11/2015 C++ Coding Standard Comment All Questions a Programmer May Have When Looking at Your Code Make Your Code Discoverable by Browsing Write Comments as You Code Make Gotchas Explicit Interface and Implementation Documentation Directory Documentation Include Statement Documentation Block Comments 5. Complexity Management Layering Minimize Dependencies with Abstract Base Classes Liskov's Substitution Prinicple Open/Closed Principle Register/Dispatch Idiom Delegation Follow the Law of Demeter Design by Contract 6. Classes Naming Class Files Class Layout What should go in public/protected/private? Prototype Source File Use Header File Guards Required Methods for a Class Method Layout Formating Methods with Multiple Arguments Different Accessor Styles Init Idiom for Initializing Objects Initialize all Variables Minimize Inlines Think About What Work to do in Constructors Don't Over Use Operators Thin vs. Thick Class Interfaces Short Methods In a Source file Indicate if a Method is Static or Virtual 7. Process Use a Design Notation and Process Using Use Cases Using Stories Unified Modeling Language Code Reviews Create a Source Code Control System Early and Not Often Create a Bug Tracking System Early and Not Often Create a Wiki System Early and Not Often RCS Keyword, Change Log, and History Policy Honor Responsibilities Process Automation Tools Agreement Non­Blocking Scheduling Using Personas Use a Continuous Build System Code in the Dominant Style Run Unit Tests Before Every Check­in 8. Formatting Brace {} Policy Indentation/Tabs/Space Policy Parens () with Key Words and Functions Policy 2/86 6/11/2015 C++ Coding Standard A Line Should Not Exceed 78 Characters If Then Else Formatting switch Formatting Use of goto,continue,break and ?: One Statement Per Line Alignment of Declaration Blocks Document Null Statements Include static and virtual Key Words in Source File 9. Exceptions Create One Exception for Each Library Selecting Between Exceptions And Asserts Be Careful Throwing Exceptions in Destructors Working With Libaries Using All Sorts of Different Policies 10. Templates 11. Namespaces Create Unique Name Space Names Don't Globally Define using Create Shortcut Names 12. Miscellaneous Be Const Correct Placement of the Const Qualifier Use Streams No Magic Numbers Error Return Check Policy To Use Enums or Not to Use Enums Macros Do Not Default If Test to Non­Zero The Bull of Boolean Types Usually Avoid Embedded Assignments Reusing Your Hard Work and the Hard Work of Others Commenting Out Large Code Blocks Use #if Not #ifdef Creating a C Function in C++ Mixing C and C++ No Data Definitions in Header Files Make Functions Reentrant Use the Resource Acquisition is Initialization (RAII) Idiom Remove Trailing Whitespace 13. Portability Use Typedefs for Types Alignment of Class Members Compiler Dependent Exceptions Compiler Dependent RTTI 14. Popular Myths Promise of OO You can't use OO and C++ on Embedded Systems Introduction 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 3/86 6/11/2015 C++ Coding Standard certainly open to local amendments. Good Points When 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 4/86 6/11/2015 C++ Coding Standard 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 DUMBSHIT! | | | | IT |<‐‐‐‐| KNOW? | +‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+ | | +‐‐‐‐‐‐+ +‐‐‐‐‐‐‐‐‐‐‐‐‐+ | | | | | | | V | | | +‐‐‐‐‐‐‐‐‐‐‐‐‐+ +‐‐‐‐‐‐‐‐‐‐‐‐‐+ | | | | YOU POOR | YES | WILL YOU | | | | | BASTARD |<‐‐‐‐‐‐| CATCH HELL? |<‐‐‐‐‐+ | | +‐‐‐‐‐‐‐‐‐‐‐‐‐+ +‐‐‐‐‐‐‐‐‐‐‐‐‐+ | | | | | | | | NO | | V V | V +‐‐‐‐‐‐‐‐‐‐‐‐‐+ +‐‐‐‐‐‐‐‐‐‐‐‐+ +‐‐‐‐‐‐‐‐‐‐‐‐‐‐>| STOP |<‐‐‐‐‐‐| SHITCAN IT | +‐‐‐‐‐‐‐‐‐‐‐‐‐+ +‐‐‐‐‐‐‐‐‐‐‐‐+ Leadership I wish i had said this, but it was said by [email protected] in comp.software­eng. 5/86 6/11/2015 C++ Coding Standard 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 Code Reviews. If you are interested in coding standards you may also be interested in Code Review Standards I have created at . Design Stories OO Info Sources Designing Qt­Style C++ APIs ­ A good paper on API I design for C++. I don't agree with everything, but it is good. Unified Modeling Language (UML) OO FAQ ­ All You Wanted to Know About OO C++ FAQ LITE C++ Source Libraries C++ Tutorials ACE C++ Library Collection of Other Standards Design by Contract from Eiffle C++ isn't Perfect, Here are Some Reasons Why Doxygen ­ is a 'javadoc' like utility that extracts comments and relevant information from your C++/C programs and generates HTML pages from it. Const Correctness ­ A very nice article on const correctness by Chad Loder. Abraxis Code Check ­ A program for checking code for coding standard violations and other problems. 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 6/86 6/11/2015 C++ Coding Standard 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: 7/86 6/11/2015 C++ Coding Standard 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 8/86 6/11/2015 C++ Coding Standard 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 JJ as 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 9/86 6/11/2015 C++ Coding Standard 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 10/86 6/11/2015 C++ Coding Standard 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. Reference Variables and Functions Returning References References should be prepended with 'r'. Justification The difference between variable types is clarified. It establishes the difference between a method returning a modifiable object and the same method name returning a non­modifiable object. Example 11/86 6/11/2015 C++ Coding Standard class Test { public: void DoSomething(StatusInfo& rStatus); StatusInfo& rStatus(); const StatusInfo& Status() const; private: StatusInfo& mrStatus; } Global Variables Global variables should be prepended with a 'g'. Justification It's important to know the scope of a variable. Example Logger gLog; Logger* gpLog; Global Constants Global constants should be all caps with '_' separators. Justification It's tradition for global constants to named this way. You must be careful to not conflict with other global #defines and enum labels. Example const int A_GLOBAL_CONSTANT= 5; Static Variables Static variables may be prepended with 's'. Justification It's important to know the scope of a variable. Example class Test { 12/86 6/11/2015 C++ Coding Standard public: private: static StatusInfo msStatus; } Type Names When possible for types based on native types make a typedef. Typedef names should use the same naming policy as for a class with the word Type appended. Justification Of all the different naming strategies many people found this one the best compromise. Types are things so should use upper case letters. Type is appended to make it clear this is not a class. Example typedef uint16 ModuleType; typedef uint32 SystemType; Enum Names Labels All Upper Case with '_' Word Separators This is the standard rule for enum labels. Example enum PinStateType { PIN_OFF, PIN_ON }; Enums as Constants without Class Scoping Sometimes people use enums as constants. When an enum is not embedded in a class make sure you use some sort of differentiating name before the label so as to prevent name clashes. Example enum PinStateType If PIN was not prepended a conflict { would occur as OFF and ON are probably PIN_OFF, already defined. PIN_ON }; 13/86 6/11/2015 C++ Coding Stand...
View Full Document

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern