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 a 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 CamelCase with a leading capital letter, with no underscores. Enumerated type constants use the same convention as class constants, i.e. all uppercase with underscores.
192 // classes and structs
193 class UrlTable { ... };
194 class UrlTableTester { ... };
195 struct UrlTableProperties { ... };
198 typedef hash_map<UrlTableProperties *, string> PropertiesMap;
212 <H2>Variable Names</H2>
214 Variable names should use camel case, with an initial lower case letter.
215 Local variable names start with a lowercase letter. 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 Avoid underscore characters in mixed case names.
220 Constants should be all upper case, with underscores between words.
221 Global variables should be avoided, however, 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">
231 string tableName; // OK - starts lowercase
232 string tablename; // OK - all lowercase.
236 string TableName; // Bad - starts with capital.
243 string mTableName; // OK.
250 string tableName; // OK.
254 const int DAYS_IN_A_WEEK = 7;
257 const int DaysInAWeek = 7; // Bad - constants should not use camel case.
258 const int DAYSINAWEEK = 7; // Bad - without underscore, words run together.
264 <H2>Function Names</H2>
266 Regular function names are written in camel case starting with a
267 capital letter and no underscores; accessors and mutators match
268 the name of the variable with Get or Set as prefix.
270 <H3>Examples <input type="button" value="Hide" onclick="toggleVisibility( this, 'function_name_examples' );"/></H3>
271 <ARTICLE class="detail" id="function_name_examples">
273 void MyExcitingFunction();
274 void MyExcitingMethod();
280 int GetNumEntries() const { return mNumEntries; }
281 void SetNumEntries( int numEntries ) { mNumEntries = numEntries; }
289 void my_boring_function(); // bad - uses underscores and no camel case.
298 Macros should not be used for programming, code should always be readable without preprocessor.
299 Only allowed cases for macros are include guards, debug tracing and compile time feature flags
300 <b>inside</b> .cpp files when no other variation mechanism is not possible. Always prefer variation
301 through design and template mechanisms rather than <i>#define</i>.
302 If you need to use macros, they're like this: <code>MY_MACRO_THAT_SCARES_SMALL_CHILDREN</code>.
304 <H3>Examples <input type="button" value="Hide" onclick="toggleVisibility( this, 'macro_name_examples' );"/></H3>
305 <ARTICLE class="detail" id="macro_name_examples">
307 #define DEBUG_TRACE( __FILE__, __LINE__ ) ...
318 Comments are absolutely vital to keeping our code readable.
319 The following rules describe what you should comment and where.
320 But remember: while comments are very important, the best code is self-documenting.
321 Giving sensible names to types and variables is much better than using obscure
322 names that you must then explain through comments.
323 When writing your comments, write for your audience: the next
324 contributor who will need to understand your code.
326 <H2>Comment Rules <input type="button" value="Hide" onclick="toggleVisibility( this, 'comments_details' );"/></H2>
327 <ARTICLE class="detail" id="comments_details">
328 <H3>Comment Style</H3>
330 API documentation must use doxygen comments: /** */ or /// <BR>
331 Internal comments can use <CODE>//</CODE> or <CODE>/* */</CODE> syntax, as long
332 as you are consistent.
334 <H3>File Comments</H3>
336 Start each header file with a guard macro.<BR>
337 This should match the name of the class which is defined in the file,
338 including the namespace.<BR>
339 For example, a class in the Dali namespace called Actor would have the guard:<BR><BR> __DALI_ACTOR_H__<BR><BR>
340 An Actor class in the Dali::Internal namespace would have the guard:<BR><BR> __DALI_INTERNAL_ACTOR_H__<BR><BR>
341 The copyright & legal notice should follow the guard macro (inside the #ifdef), since this will improve build times.<BR><BR>
342 Start each source file with the copyright & legal notice.
344 <H3>Class Comments</H3>
346 Every class definition should have an accompanying comment that
347 describes what it is for and how it should be used. It should have
348 a brief description, followed by a newline and a broader description.
352 * @brief Iterates over the contents of a GargantuanTable.
355 * GargantuanTableIterator* iter = table->NewIterator();
356 * for( iter->Seek("foo"); !iter->done(); iter->Next() )
358 * process( iter->key(), iter->value() );
362 class GargantuanTableIterator
368 Document the synchronization assumptions the class makes, if
369 any. If an instance of the class can be accessed by multiple
370 threads, take extra care to document the rules and invariants
371 surrounding multithreaded use.
373 <H3>Function Comments</H3>
375 Every function declaration in a header file must have a brief comment
376 that describes what the function does, followed by a newline. It may
377 be followed by a detailed description on how to use it.
378 These comments should be descriptive ("Opens the file") rather than
379 imperative ("Open the file"); the
380 comment describes the function, it does not tell the function what to do.
381 Each parameter must be documented, as must any return value.
384 Types of things to mention in comments at the function
388 <LI> What the inputs and outputs are.</LI>
389 <LI> For class member functions: whether the object
390 remembers reference arguments beyond the
391 duration of the method call, and whether it will
392 free them or not. </LI>
393 <LI> If the function allocates memory that the caller
395 <LI> Whether any of the arguments can be <CODE>NULL</CODE> </LI>
396 <LI> If there are any performance implications of how a function is used.</LI>
397 <LI> If the function is re-entrant. What are its synchronization assumptions? </LI>
401 * @brief Get the iterator for this data table.
403 * It is the client's responsibility to delete the iterator,
404 * and it must not use the iterator once the GargantuanTable object
405 * on which the iterator was created has been deleted.
407 * The iterator is initially positioned at the beginning of the table.
409 * This method is equivalent to:
410 * Iterator* iter = table->NewIterator();
413 * If you are going to immediately seek to another place in the
414 * returned iterator, it will be faster to use NewIterator()
415 * and avoid the extra seek.
416 * @return an iterator for this table.
418 Iterator* GetIterator() const;
421 When commenting constructors and destructors, remember that
422 the person reading your code knows what constructors and
423 destructors are for, so comments that just say something like
424 "destroys this object" are not useful.
426 <H3>Variable Comments</H3>
428 In general the actual name of the variable should be descriptive
429 enough to give a good idea of what the variable is used for. In
430 certain cases, more comments are required - use Doxygen formatting.
435 * @brief Keeps track of the total number of entries in the table.
437 * Used to ensure we do not go over the limit. -1 means
438 * that we don't yet know how many entries the table has.
440 int mNumTotalEntries;
442 float mDuration; ///< Duration in seconds.
445 <H3> Duplicate documentation</H3>
447 Try to avoid duplicate documentation by using the @copydoc command.
450 @copydoc copies a documentation block from the object specified by
451 link-object and pastes it at the location of the command.
452 This command can be useful to avoid cases where a documentation block
453 would otherwise have to be duplicated or it can be used to extend the
454 documentation of an inherited member.
458 * @copydoc MyClass::myfunction()
459 * More documentation.
463 If the member is overloaded, you should specify the argument types
464 explicitly (without spaces!), like in the following:
467 /** @copydoc MyClass::myfunction(type1,type2) */
469 <H3>Punctuation, Spelling and Grammar</H3>
471 Pay attention to punctuation, spelling, and grammar; it is
472 easier to read well-written comments than badly written ones.
475 Comments should usually be written as complete
476 sentences with proper capitalization and periods at the end.
477 Shorter comments, such as comments at the end of a line of
478 code, can sometimes be less formal, but you should be
479 consistent with your style. Complete sentences are more
480 readable, and they provide some assurance that the comment is
481 complete and not an unfinished thought.
483 <H3>TODO Comments</H3>
485 Use <code>TODO</code> comments for code that is temporary, a
486 short-term solution, or good-enough but not perfect.
488 <H3>Deprecation Comments</H3>
490 Mark deprecated interface points with <code>@deprecated</code> comments.
492 <H3>Doxygen Tags</H3>
494 The following order should be followed when using doxygen tags for functions, classes, structs etc.
498 * @deprecated DALi X.X.X Mandatory, if applicable // Version deprecated and alternative
499 * @brief Mandatory // Explain the API briefly
500 * @details Optional // Explain the API in more detail. Use this tag or add more
501 * // information after a blank line following the @brief
502 * @since DALi X.X.X Mandatory // Version added
503 * @param[in] Mandatory, if applicable // In Parameter list
504 * @param[out] Mandatory, if applicable // Out Parameter list
505 * @param[in,out] Mandatory, if applicable // In/Out Parameter list
506 * @return Mandatory, if applicable // Return value
507 * @pre Optional // Pre-condition
508 * @post Optional // Post-condition
509 * @note Optional // Any notes that apply
510 * @see Optional // Other related APIs
514 Where X.X.X is the next release version (ensure you're patch gets merged before the release).
521 A project is much easier to follow if everyone uses the same style.
522 It is important that all contributors follow the style rules so that
523 they can all read and understand everyone's code easily.
526 <H2>Formatting Rules <input type="button" value="Hide" onclick="toggleVisibility( this, 'formatting_rules' );"/></H2>
527 <ARTICLE class="detail" id="formatting_rules">
530 <LI>Use only spaces, and indent 2 spaces at a time</LI>
531 <LI>Avoid unnecessary trailing whitescape</LI>
532 <LI>Avoid overly long lines, modern screens and editors can handle upto 120 characters</LI>
533 <LI>Use UTF-8 formatting for non-ASCII characters</LI>
534 <LI>Anything enclosed in parentheses should also have a space inside the parentheses. </LI>
535 <LI>Braces must each be in a line on their own.</LI>
538 Hex encoding is also OK, and encouraged where it enhances
539 readability — for example, <code>"\xEF\xBB\xBF"</code> is the
540 Unicode zero-width no-break space character, which would be
541 invisible if included in the source as straight UTF-8.
544 <H3>Class Format</H3>
546 Sections in <code>public</code>, <code>protected</code> and
547 <code>private</code> order.
548 Typedefs and Enums first, Constructor(s) & Destructors & public API next, then virtual methods and implementation details last.
552 * @brief Class purpose.
556 class MyClass : public Base
561 * @brief Short description.
565 MyClass(); // 2 space indent.
568 * @brief Short description.
570 * @param[in] var Description
572 explicit MyClass( int var );
575 * @brief Short description.
582 * @brief Short description.
589 * @brief Short description.
593 void SomeFunctionThatDoesNothing();
596 * @brief Short description.
599 * @param[in] var Parameter description
601 void SetSomeVar( int var )
604 * @brief Short description.
607 * @return value description.
609 int GetSomeVar() const
611 private: // Implementation
613 MyClass( MyClass& aRHs ); ///< no copying
614 MyClass& operator=( const MyClass& aRHs ); ///< no copying.
615 bool SomeInternalFunction();
617 int mSomeVar; ///< short description.
618 int mSomeOtherVar; ///< short description.
622 <H3>Constructor Initializer Lists</H3>
624 Constructor initializer lists can be all on one line or with subsequent lines indented.
625 Always initialize things in declaration order, base class first!!
628 // When it all fits on one line:
629 MyClass::MyClass( int var ) : Base( var), mSomeVar( var ), mSomeOtherVar( var + 1 )
633 // When it requires multiple lines, indent, putting the colon on
634 // the first initializer line:
635 MyClass::MyClass( int var )
638 mSomeOtherVar( var + 1 )
644 <H3>Namespace Formatting</H3>
646 The contents of namespaces are not indented.
653 { // Correct. No extra indentation within namespace.
660 When declaring nested namespaces, put each namespace on its own line.
664 * @brief description of namespace
670 * @brief description of namespace
676 <H3>Function Declarations and Definitions</H3>
678 Return type on the same line as function name, parameters on the same line if they fit.
679 All parameters should be named, with identical names in the declaration and definition.
682 ReturnType ClassName::FunctionName( Type parameterName1, Type parameterName2 )
688 If you have too much text to fit on one line:
691 ReturnType ClassName::ReallyLongFunctionName( Type parameterName1,
693 Type parameterName3 )
699 or if you cannot fit even the first parameter:
702 ReturnType LongClassName::ReallyReallyReallyLongFunctionName(
703 Type parameterName1, // 2 space indent
705 Type parameterName3 )
707 DoSomething(); // 2 space indent
712 <code>const</code> keyword should be on the same line as the last parameter:
715 // Everything in this function signature fits on a single line
716 ReturnType FunctionName( Type parameter ) const
721 // This function signature requires multiple lines, but
722 // the const keyword is on the line with the last parameter.
723 ReturnType ReallyLongFunctionName( Type parameter1,
724 Type parameter2 ) const
730 If some parameters are unused, comment out the variable name in the function definition:
733 // Always have named parameters in interfaces.
737 virtual void Rotate( double radians ) = 0;
740 // Always have named parameters in the declaration.
741 class Circle : public Shape
744 virtual void Rotate( double radians );
747 // Comment out unused named parameters in definitions.
748 void Circle::Rotate( double /*radians*/ )
753 // Bad - if someone wants to implement later, it's not clear what the
755 void Circle::Rotate( double )
760 <H3>Function Calls</H3>
762 On one line if it fits; otherwise, wrap arguments at the parenthesis. Put one space inside the parentheses, none outside.
766 bool retval = DoSomething( argument1, argument2, argument3 );
769 If the arguments do not all fit on one line, they should be
770 broken up onto multiple lines, with each subsequent line
771 aligned with the first argument:
774 bool retval = DoSomething( aVeryVeryVeryVeryLongArgument1,
775 argument2, argument3 );
778 If the function has many arguments, consider having one per
779 line if this makes the code more readable:
782 bool retval = DoSomething( argument1,
788 If the function signature is so long that it cannot fit,
789 place all arguments on subsequent lines:
794 DoSomethingThatRequiresALongFunctionName(
795 aVeryLongArgument1, // indent
802 <H3>Conditionals</H3>
804 The <code>if</code> statement should be followed only by the conditional, with a space inside the parentheses, not outside. The following clause must always be surrounded by braces on separate lines.
805 The <code>else</code> keyword belongs on its own line, and the following clause must always be
806 surrounded by braces.
809 if( condition ) // space inside parentheses
819 if(condition) // Bad - space missing inside parentheses
820 if(condition){ // Doubly bad. Mis-aligned parentheses are harder to read.
823 Must always have curly braces for the clauses, and they must always be on a line
829 DoSomething(); // 2 space indent.
833 DoSomethingElse(); // 2 space indent.
837 <H3>Loops and Switch Statements</H3>
839 Switch statements use braces for blocks. Empty loop bodies must use
840 <code>{}</code> or <code>continue</code>.
841 Switch statements should always have a <code>default</code> case
842 unless they switch on an <code>enum</code> type,
843 for which the compiler will ensure all values are handled.
845 If the default case should never execute, simply <code>assert</code>.
846 Put one space inside the parentheses, none outside.
849 <code>case</code> blocks in <code>switch</code> statements must have
851 They should be placed as shown below.
857 case 0: // 2 space indent
859 ... // 2 space indent
869 DALI_ASSERT_ALWAYS( false );
874 Empty loop bodies should use <code>{}</code> or
875 <code>continue</code>, but not a single semicolon.
880 // Repeat test until it returns false.
883 for( int i = 0; i < someNumber; ++i )
885 } // Good - empty body, clearly separated.
888 continue; // Good - continue indicates no logic.
892 while( condition ); // Bad - looks like part of do/while loop.
894 <H3>Pointer and Reference Expressions</H3>
896 No spaces around period or arrow. Pointer operators do not have trailing spaces.
899 The following are examples of correctly-formatted pointer and
900 reference expressions:
909 When declaring a pointer variable or argument, you may place
910 the asterisk adjacent to either the type or to the variable
911 name, however, placing with the type is preferred.
914 // These are fine, space preceding.
916 const string &str;
918 // These are fine, space following.
919 char* c; // but remember to do each variable on its own line or "char* c, *d, *e, ...;"!
920 const string& str;
923 char * c; // Bad - spaces on both sides of *
924 const string & str; // Bad - spaces on both sides of &
927 You should do this consistently within a single file,
928 so, when modifying an existing file, use the style in that file.
931 <H3>Boolean Expressions</H3>
933 When you have a boolean expression that is long, be consistent in
934 how you break up the lines.
937 In this example, the logical AND operator is always at the end
941 if( thisOneThing > thisOtherThing &&
942 aThirdThing == aFourthThing &&
943 yetAnother && lastOne )
949 <H3>Return Values</H3>
951 Do not needlessly surround the <code>return</code> expression with parentheses.
954 return result; // No parentheses in the simple case.
955 return ( someLongCondition && // Parentheses ok to make a complex
956 anotherCondition ); // expression more readable.
959 return (value); // You wouldn't write var = (value);
960 return(result); // return is not a function!
962 <H3>Variable and Array Initialization</H3>
964 Your choice of <code>=</code> or <code>()</code>.
967 You may choose between <code>=</code> and <code>()</code>; the
968 following are all correct:
973 string name( "Some Name" );
974 string name = "Some Name";
977 <H3>Preprocessor Directives</H3>
979 Preprocessor directives should not be indented but should
980 instead start at the beginning of the line.
983 Even when pre-processor directives are within the body of
984 indented code, the directives should start at the beginning of
988 // Good - directives at beginning of line
991 #if DISASTER_PENDING // Correct -- Starts at beginning of line
998 // Bad - indented directives
1001 #if DISASTER_PENDING // Wrong! The "#if" should be at beginning of line
1003 #endif // Wrong! Do not indent "#endif"
1010 <P>Thats all folks, if you read this far you are now all equipped to write good code :) !! </P>