3 <TITLE>Dali C++ Coding Style</TITLE>
5 green code for good examples, same formatting as <pre> tag
6 red code for bad examples, same formatting as <pre> tag
7 details hidden by default
9 <style type="text/css">
10 code.good { color:green; white-space:pre; }
11 code.bad { color:red; white-space:pre; }
12 article.detail { display:block; }
15 <script type="text/javascript">
16 function toggleVisibility( button, obj )
18 // must have button and object
21 var e=document.getElementById( obj );
25 // initially display property seems to be empty, then none
26 if( e.style.display == "" || e.style.display == "none" )
30 e.style.display="block";
36 e.style.display="none";
46 The most important consistency rules are those that govern
47 naming. The style of a name immediately informs us what sort of
48 thing the named entity is: a type, a variable, a function, a
49 constant, a macro, etc., without requiring us to search for the
50 declaration of that entity. The pattern-matching engine in our
51 brains relies a great deal on these naming rules.
54 Consistency is more important than individual preferences so regardless of
55 whether you find them sensible or not, the rules are the rules.
59 <H2>General Naming Rules</H2>
61 Function names, variable names, and filenames should be
62 descriptive; eschew abbreviation. Types and variables should be
63 nouns, while functions should be "command" verbs.
65 <H3>How to Name <input type="button" value="Hide" onclick="toggleVisibility( this, 'how_to_name' );"/></H3>
66 <ARTICLE class="detail" id="how_to_name">
68 Give as descriptive a name as possible, within reason. Do
69 not worry about saving horizontal space as it is far more
70 important to make your code immediately understandable by a
71 new reader. Examples of well-chosen names:
74 int numberOfErrors; // Good.
75 int countCompletedConnections; // Good.
78 Poorly-chosen names use ambiguous abbreviations or arbitrary
79 characters that do not convey meaning:
82 int n; // Bad - meaningless.
83 int nerr; // Bad - ambiguous abbreviation.
84 int n_comp_conns; // Bad - ambiguous abbreviation.
87 Type and variable names should typically be nouns: e.g.,
88 <code>FileOpener</code>,
89 <code>NumErrors</code>.
92 Function names should typically be imperative (that is they should be commands):
93 e.g., <code>OpenFile()</code>, <code>set_num_errors()</code>. There is an exception for
94 accessors, which should be named the same as the variable they access.
98 <H3>Abbreviations <input type="button" value="Hide" onclick="toggleVisibility( this, 'abbreviations' );"/></H3>
99 <ARTICLE class="detail" id="abbreviations">
101 Do not use abbreviations unless they are extremely well
102 known outside your project. For example:
106 // These show proper names with no abbreviations.
107 int numberOfDnsConnections; // Most people know what "DNS" stands for.
108 int priceCountReader; // OK, price count. Makes sense.
112 // Abbreviations can be confusing or ambiguous outside a small group.
113 int wgcconnections; // Only your group knows what this stands for.
114 int pcreader; // Lots of things can be abbreviated "pc".
117 Never abbreviate by leaving out letters:
120 int error_count; // Good.
123 int error_cnt; // Bad.
131 Filenames should be all lowercase and can include underscores dashes (<code>-</code>).
132 Do not use underscores in filenames (<code>_</code>).
134 <H3>Examples <input type="button" value="Hide" onclick="toggleVisibility( this, 'file_name_examples' );"/></H3>
135 <ARTICLE class="detail" id="file_name_examples">
137 Examples of acceptable file names:
143 myusefulclass-test.cpp
147 C++ files should end in <code>.cpp</code> and header files
148 should end in <code>.h</code>.
151 Do not use filenames that already exist
152 in <code>/usr/include</code>, such as <code>db.h</code>.
155 In general, make your filenames very specific. For example,
156 use <code>http-server-logs.h</code> rather than <code>logs.h</code>.
157 A class called <code>FooBar</code> should be declared in file
158 called <code>foobar.h</code> and defined in <code>foobar.cpp</code>.
161 Inline functions must be in a <code>.h</code> file. If your
162 inline functions are very short, they should go directly into your
163 <code>.h</code> file. However, if your inline functions
164 include a lot of code, they may go into a third file that
165 ends in <code>-inl.h</code>. In a class with a lot of inline
166 code, your class could have three files:
169 foobar.h // The class declaration.
170 foobar.cpp // The class definition.
171 foobar-inl.h // Inline functions that include lots of code.
179 Type names start with a capital letter and have a capital
180 letter for each new word, with no underscores:
181 <code>MyExcitingClass</code>, <code>MyExcitingEnum</code>.
182 All type names are declared inside namespace so no prefixing is used.
184 <H3>Examples <input type="button" value="Hide" onclick="toggleVisibility( this, 'type_name_examples' );"/></H3>
185 <ARTICLE class="detail" id="type_name_examples">
187 The names of all types; classes, structs, typedefs have the same naming convention.
188 Type names start with a capital letter and have a capital letter for each new word (CamelCase).
189 No underscores. Enumerated types use same convention as Constants> all capitals.
193 // classes and structs
195 class UrlTableTester { ...
196 struct UrlTableProperties { ...
199 typedef hash_map<UrlTableProperties *, string> PropertiesMap;
213 <H2>Variable Names</H2>
215 Local variable names start with a lowercase. For example: <code>myExcitingLocalVariable</code>,
216 Class member variables have prefix m. For example: <code>mMember</code>.
217 The only exception to this rule is for public member variables in public structs where the prefix m is not required.
218 Such member variables should also start with a lowercase letter.
219 Constants should be all capitals.
220 Avoid underscore characters in names because it can be hard to spot.
221 Global variables should be avoided, if one is needed, prefix it with <code>g</code>.
223 <H3>Examples <input type="button" value="Hide" onclick="toggleVisibility( this, 'variable_name_examples' );"/></H3>
224 <ARTICLE class="detail" id="variable_name_examples">
229 string tableName; // OK - starts lowercase
230 string tablename; // OK - all lowercase.
233 string TableName; // Bad - starts with capital.
239 string mTableName; // OK.
243 const int DAYSINAWEEK = 7;
249 <H2>Function Names</H2>
251 Regular functions have camel case starting with uppercase; accessors and mutators match
252 the name of the variable with Get or Set as prefix. No underscores
254 <H3>Examples <input type="button" value="Hide" onclick="toggleVisibility( this, 'function_name_examples' );"/></H3>
255 <ARTICLE class="detail" id="function_name_examples">
257 MyExcitingFunction();
264 int GetNumEntries() const { return mNumEntries; }
265 void SetNumEntries(int numEntries) { mNumEntries = numEntries; }
277 Macros should not be used for programming, code should always be readable without preprocessor.
278 Only allowed cases for macros are include guards, debug tracing and compile time feature flags
279 <b>inside</b> .cpp files when no other variation mechanism is not possible. Always prefer variation
280 through design and template mechanisms rather than <i>#define</i>.
281 If you need to use macros, they're like this: <code>MY_MACRO_THAT_SCARES_SMALL_CHILDREN</code>.
283 <H3>Examples <input type="button" value="Hide" onclick="toggleVisibility( this, 'macro_name_examples' );"/></H3>
284 <ARTICLE class="detail" id="macro_name_examples">
286 #define DEBUG_TRACE( __FILE__, __LINE__ ) ...
290 #endif // __ACTOR_H__
297 Comments are absolutely vital to keeping our code readable.
298 The following rules describe what you should comment and where.
299 But remember: while comments are very important, the best code is self-documenting.
300 Giving sensible names to types and variables is much better than using obscure
301 names that you must then explain through comments.
302 When writing your comments, write for your audience: the next
303 contributor who will need to understand your code.
305 <H2>Comment Rules <input type="button" value="Hide" onclick="toggleVisibility( this, 'comments_details' );"/></H2>
306 <ARTICLE class="detail" id="comments_details">
307 <H3>Comment Style</H3>
309 API documentation must use doxygen comments: /** */ or /// <BR>
310 Internal comments can use <CODE>//</CODE> or <CODE>/* */</CODE> syntax, as long
311 as you are consistent.
313 <H3>File Comments</H3>
315 Start each header file with a guard macro.<BR>
316 This should match the name of the class which is defined in the file,
317 including the namespace.<BR>
318 For example, a class in the Dali namespace called Actor would have the guard:<BR><BR> __DALI_ACTOR_H__<BR><BR>
319 An Actor class in the Dali::Internal namespace would have the guard:<BR><BR> __DALI_INTERNAL_ACTOR_H__<BR><BR>
320 The copyright & legal notice should follow the guard macro (inside the #ifdef), since this will improve build times.<BR><BR>
321 Start each source file with the copyright & legal notice.
323 <H3>Class Comments</H3>
325 Every class definition should have an accompanying comment that
326 describes what it is for and how it should be used.
330 * Iterates over the contents of a GargantuanTable.
332 * GargantuanTableIterator* iter = table->NewIterator();
333 * for (iter->Seek("foo"); !iter->done(); iter->Next()) {
334 * process(iter->key(), iter->value());
338 class GargantuanTableIterator
344 Document the synchronization assumptions the class makes, if
345 any. If an instance of the class can be accessed by multiple
346 threads, take extra care to document the rules and invariants
347 surrounding multithreaded use.
349 <H3>Function Comments</H3>
351 Every function declaration (typically in a header file) must have comments immediately
352 preceding it that describe what the function does and how to use it. These comments
353 should be descriptive ("Opens the file") rather than imperative ("Open the file"); the
354 comment describes the function, it does not tell the function what to do.
357 Types of things to mention in comments at the function
361 <LI> What the inputs and outputs are.</LI>
362 <LI> For class member functions: whether the object
363 remembers reference arguments beyond the
364 duration of the method call, and whether it will
365 free them or not. </LI>
366 <LI> If the function allocates memory that the caller
368 <LI> Whether any of the arguments can be <CODE>NULL</CODE> </LI>
369 <LI> If there are any performance implications of how a function is used.</LI>
370 <LI> If the function is re-entrant. What are its synchronization assumptions? </LI>
374 * Get the iterator for this data table. Client's responsibility is to delete the iterator,
375 * and it must not use the iterator once the GargantuanTable object
376 * on which the iterator was created has been deleted.
378 * The iterator is initially positioned at the beginning of the table.
380 * This method is equivalent to:
381 * Iterator* iter = table->NewIterator();
384 * If you are going to immediately seek to another place in the
385 * returned iterator, it will be faster to use NewIterator()
386 * and avoid the extra seek.
387 * @return an iterator for this table.
389 Iterator* GetIterator() const;
392 When commenting constructors and destructors, remember that
393 the person reading your code knows what constructors and
394 destructors are for, so comments that just say something like
395 "destroys this object" are not useful.
397 <H3>Variable Comments</H3>
399 In general the actual name of the variable should be descriptive
400 enough to give a good idea of what the variable is used for. In
401 certain cases, more comments are required.
405 // Keeps track of the total number of entries in the table.
406 // Used to ensure we do not go over the limit. -1 means
407 // that we don't yet know how many entries the table has.
408 int mNumTotalEntries;
410 <H3> Duplicate documentation</H3>
412 Try to avoid duplicate documentation by using the @copydoc command.
415 @copydoc copies a documentation block from the object specified by
416 link-object and pastes it at the location of the command.
417 This command can be useful to avoid cases where a documentation block
418 would otherwise have to be duplicated or it can be used to extend the
419 documentation of an inherited member.
422 /*! @copydoc MyClass::myfunction()
423 * More documentation.
427 if the member is overloaded, you should specify the argument types
428 explicitly (without spaces!), like in the following:
431 /*! @copydoc MyClass::myfunction(type1,type2) */
433 <H3>Punctuation, Spelling and Grammar</H3>
435 Pay attention to punctuation, spelling, and grammar; it is
436 easier to read well-written comments than badly written ones.
439 Comments should usually be written as complete
440 sentences with proper capitalization and periods at the end.
441 Shorter comments, such as comments at the end of a line of
442 code, can sometimes be less formal, but you should be
443 consistent with your style. Complete sentences are more
444 readable, and they provide some assurance that the comment is
445 complete and not an unfinished thought.
447 <H3>TODO Comments</H3>
449 Use <code>TODO</code> comments for code that is temporary, a
450 short-term solution, or good-enough but not perfect.
452 <H3>Deprecation Comments</H3>
454 Mark deprecated interface points with <code>DEPRECATED</code> comments.
461 A project is much easier to follow if everyone uses the same style.
462 It is important that all contributors follow the style rules so that
463 they can all read and understand everyone's code easily.
466 <H2>Formatting Rules <input type="button" value="Hide" onclick="toggleVisibility( this, 'formatting_rules' );"/></H2>
467 <ARTICLE class="detail" id="formatting_rules">
470 <LI>Use only spaces, and indent 2 spaces at a time</LI>
471 <LI>Avoid unnecessary trailing whitescape</LI>
472 <LI>Avoid overly long lines, modern screens and editors can handle upto 120 characters</LI>
473 <LI>Use UTF-8 formatting for non-ASCII characters</LI>
476 Hex encoding is also OK, and encouraged where it enhances
477 readability — for example, <code>"\xEF\xBB\xBF"</code> is the
478 Unicode zero-width no-break space character, which would be
479 invisible if included in the source as straight UTF-8.
482 <H3>Class Format</H3>
484 Sections in <code>public</code>, <code>protected</code> and
485 <code>private</code> order.
486 Typedefs and Enums first, Constructor(s) & Destructors & public API next, then virtual methods and implementation details last.
491 * Class documentation
493 class MyClass : public Base
500 MyClass(); // 2 space indent.
505 explicit MyClass( int var );
510 virtual ~MyClass() {}
520 void SomeFunctionThatDoesNothing();
525 void SetSomeVar( int var )
530 int GetSomeVar() const
532 private: // Implementation
534 MyClass( MyClass& aRHs ); // no copying
535 MyClass& operator=( const MyClass& aRHs ); // no copying.
536 bool SomeInternalFunction();
543 <H3>Constructor Initializer Lists</H3>
545 Constructor initializer lists can be all on one line or with subsequent lines indented.
546 Always initialize things in declaration order, base class first!!
549 // When it all fits on one line:
550 MyClass::MyClass( int var ) : Base( var), mSomeVar( var ), mSomeOtherVar( var + 1 ) {}
552 // When it requires multiple lines, indent, putting the colon on
553 // the first initializer line:
554 MyClass::MyClass( int var )
557 mSomeOtherVar( var + 1 )
563 <H3>Namespace Formatting</H3>
565 The contents of namespaces are not indented.
571 { // Correct. No extra indentation within namespace.
577 When declaring nested namespaces, put each namespace on its own line.
586 <H3>Function Declarations and Definitions</H3>
588 Return type on the same line as function name, parameters on the same line if they fit.
589 All parameters should be named, with identical names in the declaration and definition.
592 ReturnType ClassName::FunctionName( Type par_name1, Type par_name2 )
598 If you have too much text to fit on one line:
601 ReturnType ClassName::ReallyLongFunctionName( Type par_name1, Type par_name2,
608 or if you cannot fit even the first parameter:
611 ReturnType LongClassName::ReallyReallyReallyLongFunctionName(
612 Type par_name1, // indent
616 DoSomething(); // 2 space indent
621 <code>const</code> keyword should be on the same line as the last parameter:
624 // Everything in this function signature fits on a single line
625 ReturnType FunctionName( Type par ) const
630 // This function signature requires multiple lines, but
631 // the const keyword is on the line with the last parameter.
632 ReturnType ReallyLongFunctionName( Type par1,
639 If some parameters are unused, comment out the variable name in the function definition:
642 // Always have named parameters in interfaces.
646 virtual void Rotate( double radians ) = 0;
649 // Always have named parameters in the declaration.
650 class Circle : public Shape
653 virtual void Rotate( double radians );
656 // Comment out unused named parameters in definitions.
657 void Circle::Rotate(double /*radians*/) {}
660 // Bad - if someone wants to implement later, it's not clear what the
662 void Circle::Rotate( double ) {}
665 <H3>Function Calls</H3>
667 On one line if it fits; otherwise, wrap arguments at the parenthesis. Put one space inside the parentheses, none outside.
671 bool retval = DoSomething( argument1, argument2, argument3 );
674 If the arguments do not all fit on one line, they should be
675 broken up onto multiple lines, with each subsequent line
676 aligned with the first argument:
679 bool retval = DoSomething( averyveryveryverylongargument1,
680 argument2, argument3 );
683 If the function has many arguments, consider having one per
684 line if this makes the code more readable:
687 bool retval = DoSomething( argument1,
693 If the function signature is so long that it cannot fit,
694 place all arguments on subsequent lines:
699 DoSomethingThatRequiresALongFunctionName(
700 very_long_argument1, // indent
707 <H3>Conditionals</H3>
709 <code>else</code> keyword belongs on its own line. Put one space inside the parentheses, none outside.
712 if( condition ) // space inside
722 if(condition) // Bad - space missing after IF.
723 if(condition){ // Doubly bad.
726 Short conditional statements may be written on one line if
727 this enhances readability. You may use this only when the
728 line is brief and the statement does not use the
729 <code>else</code> clause.
732 if( x == kFoo ) return new Foo();
733 if( x == kBar ) return new Bar();
736 This is not allowed when the if statement has an
740 // Not allowed - IF statement on one line when there is an ELSE clause
745 In general, prefer curly braces for conditional
750 DoSomething(); // 2 space indent.
754 If one part of an <code>if</code>-<code>else</code>
755 statement uses curly braces, the other part must too:
758 // Not allowed - curly on IF but not ELSE
759 if (condition) // space outside, not inside
766 // Not allowed - curly on ELSE but not IF
775 <H3>Loops and Switch Statements</H3>
777 Switch statements use braces for blocks. Empty loop bodies must use
778 <code>{}</code> or <code>continue</code>.
779 Switch statements should always have a <code>default</code> case
780 unless they switch on an <code>enum</code> type,
781 for which the compiler will ensure all values are handled.
783 If the default case should never execute, simply <code>assert</code>.
784 Put one space inside the parentheses, none outside.
787 <code>case</code> blocks in <code>switch</code> statements must have
789 They should be placed as shown below.
795 case 0: // 2 space indent
797 ... // 2 space indent
807 DALI_ASSERT_ALWAYS( false );
812 Empty loop bodies should use <code>{}</code> or
813 <code>continue</code>, but not a single semicolon.
818 // Repeat test until it returns false.
820 for( int i = 0; i < someNumber; ++i )
821 {} // Good - empty body, clearly on its own line
823 continue; // Good - continue indicates no logic.
826 while (condition); // Bad - looks like part of do/while loop.
828 <H3>Pointer and Reference Expressions</H3>
830 No spaces around period or arrow. Pointer operators do not have trailing spaces.
833 The following are examples of correctly-formatted pointer and
834 reference expressions:
843 When declaring a pointer variable or argument, you may place
844 the asterisk adjacent to either the type or to the variable
848 // These are fine, space preceding.
850 const string &str;
852 // These are fine, space following.
853 char* c; // but remember to do each variable on its own line or "char* c, *d, *e, ...;"!
854 const string& str;
857 char * c; // Bad - spaces on both sides of *
858 const string & str; // Bad - spaces on both sides of &
861 You should do this consistently within a single file,
862 so, when modifying an existing file, use the style in that file.
865 <H3>Boolean Expressions</H3>
867 When you have a boolean expression that is long, be consistent in
868 how you break up the lines.
871 In this example, the logical AND operator is always at the end
875 if( this_one_thing > this_other_thing &&
876 a_third_thing == a_fourth_thing &&
877 yet_another && last_one )
883 <H3>Return Values</H3>
885 Do not needlessly surround the <code>return</code> expression with parentheses.
888 return result; // No parentheses in the simple case.
889 return ( some_long_condition && // Parentheses ok to make a complex
890 another_condition ); // expression more readable.
893 return (value); // You wouldn't write var = (value);
894 return(result); // return is not a function!
896 <H3>Variable and Array Initialization</H3>
898 Your choice of <code>=</code> or <code>()</code>.
901 You may choose between <code>=</code> and <code>()</code>; the
902 following are all correct:
907 string name( "Some Name" );
908 string name = "Some Name";
911 <H3>Preprocessor Directives</H3>
913 Preprocessor directives should not be indented but should
914 instead start at the beginning of the line.
917 Even when pre-processor directives are within the body of
918 indented code, the directives should start at the beginning of
922 // Good - directives at beginning of line
925 #if DISASTER_PENDING // Correct -- Starts at beginning of line
932 // Bad - indented directives
935 #if DISASTER_PENDING // Wrong! The "#if" should be at beginning of line
937 #endif // Wrong! Do not indent "#endif"
944 <P>Thats all folks, if you read this far you are now all equipped to write good code :) !! </P>