3 <TITLE>Dali C++ Coding Conventions</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";
44 <H1>General coding conventions</H1>
45 <H2>Type casting <input type="button" value="Hide" onclick="toggleVisibility( this, 'ccasts_details' );"/></H2>
46 <ARTICLE class="detail" id="ccasts_details">
48 <B>Never use C-Style Casts</B><BR>
49 The C-style cast - "(type) expr" used to convert one fundamental type to another is subject to implementation-defined effects.
50 For scalar types it can result in silent truncation of the value. For pointers and references, it does not check the
51 compatibility of the value with the target type.<BR>
52 <B>Don't cast away const, use mutable keyword instead</B><BR>
53 <B>Don't reinterpret_cast, fix the design instead</B><BR>
54 <B>Remember that reference cast will throw an error if cast fails</B><BR>
55 <B>Avoid using pointer or reference casts. They have been referred to as the goto of OO programming, fix the design instead</B><BR>
58 X* ptr = static_cast<X*>( y_ptr ); // ok, compiler checks whether types are compatible
61 (Foo*) ptr; // bad! C-cast is not guaranteed to check and never complains
67 A class interface should be complete and minimal. Class should encapsulate one thing and one thing only.
68 A complete interface allows clients to do anything they may reasonably want to do.
69 On the other hand, a minimal interface will contain as few functions as possible.
70 Class methods must be defined in the same order as they are declared. This helps navigating through code.
72 <H2>Compulsory member functions <input type="button" value="Hide" onclick="toggleVisibility( this, 'implicit_method_details' );"/></H2>
73 <ARTICLE class="detail" id="implicit_method_details">
75 Every class must define default constructor, copy constructor, assignment operator and destructor.
76 If you dont declare them, compiler will and the compiler generated versions are usually not good or safe enough.
77 If your class does not support copying, then declare copy constructor and assignment operator as private and don't define them.
80 If for example the assignment operator is not needed for a particular class, then it
81 must be declared private and not defined. Any attempt to invoke the operator will result
82 in a compile-time error. On the contrary, if the assignment operator is not declared, then
83 when it is invoked, a compiler-generated form will be created and subsequently executed.
84 This could lead to unexpected results. The same goes with default constructor and copy constructor.
89 X(); // default constructor
90 X( const X& ); // copy constructor
91 X& operator=( const X& ); // copy assignment operator
97 X(); // default constructor
99 X( const X& ) = delete; // copy constructor not allowed
100 X& operator=( const X& ); = delete; // copy assignment operator not allowed
104 <H2>Class types <input type="button" value="Hide" onclick="toggleVisibility( this, 'class_types_details' );"/></H2>
105 <ARTICLE class="detail" id="class_types_details">
107 Classes can have either <B>Value</B> semantics or <B>Pointer</B> semantics. Not both.
108 It must be clearly documented whether a class follows value or pointer semantics and this also
109 sets requirements on the class interface.
112 Classes with <B>Value</B> semantics are passed as value types. These classes provide a copy constructor,
113 a default constructor and assignment operator so that they can be copied and also stored on STL containers.
116 Classes with <B>Pointer</B> semantics are always passed through pointers, references or smart pointers.
117 These classes are ususally compound types that cannot be easily copied and thus prevent copy constructor,
118 and assignment operator. They can be only stored on STL containers through smart pointers.
121 <H2>Access Rights <input type="button" value="Hide" onclick="toggleVisibility( this, 'access_details' );"/></H2>
122 <ARTICLE class="detail" id="access_details">
124 Public and protected data should only be used in structs, not classes.
125 Roughly two types of classes exist: those that essentially aggregate data and those that provide
126 an abstraction while maintaining a well-defined state or invariant.
129 A structure should be used to model an entity that does not require an invariant (Plain Old Data)
130 A class should be used to model an entity that maintains an invariant.
131 <B>Rationale:</B> A class is able to maintain its invariant by controlling access to its data. However,
132 a class cannot control access to its members if those members non-private.
133 Hence all data in a class should be private.
136 <H2>Constructors <input type="button" value="Hide" onclick="toggleVisibility( this, 'constructor_details' );"/></H2>
137 <ARTICLE class="detail" id="constructor_details">
139 Virtual function calls are not allowed from constructor
140 Rationale: Virtual functions are resolved statically (not dynamically) in constructor
143 Member initialization order must be the same in which they are declared in the class.
144 Note: Since base class members are initialized before derived class members, base class
145 initializers should appear at the beginning of the member initialization list.
146 <B>Rationale:</B> Members of a class are initialized in the order in which they are declared—not
147 the order in which they appear in the initialization list.
150 Constructor body should not throw an exception, keep constructor simple and trivial.
151 If constructor fails, objects lifecycle never started, destructor will not be called.
154 Declare all single argument constructors as explicit thus preventing their use as implicit type convertors.
159 explicit C( int ); // good, explicit
160 C( int, int ); // ok more than one non-default argument
167 C( double ); // bad, can be used in implicit conversion
168 C( float f, int i=0 ); // bad, implicit conversion constructor
169 C( int i=0, float f=0.0 ); // bad, default constructor, but also a conversion constructor
174 <H2>Destructor <input type="button" value="Hide" onclick="toggleVisibility( this, 'destructor_details' );"/></H2>
175 <ARTICLE class="detail" id="destructor_details">
177 All classes should define a destructor, either:
179 <LI>public for value types
180 <LI>public and virtual for base classes with virtual methods
181 <LI>protected and virtual for base classes to prevent deletion (and ownership) through base class
183 This prevents undefined behavior. If an application attempts to delete a derived class object
184 through a base class pointer, the result is undefined if the base class destructor is non-virtual.
187 Virtual function calls are not allowed from inside the destructor.
188 Rationale: A class's virtual functions are resolved statically (not dynamically) in its destructor
191 All resources acquired by a class shall be released by the class's destructor.
194 Destructor is not allowed to throw an exception, avoid doing complicated things in destructor.
197 <H2>Methods <input type="button" value="Hide" onclick="toggleVisibility( this, 'method_details' );"/></H2>
198 <ARTICLE class="detail" id="method_details">
200 Don't shortcut, like use the returned reference of getter to assign a new value. If a Setter is missing, add it!
202 initial.GetPosition() = Position(10, 10); // bad!, If GetPosition is one day changed to return copy
203 // of Position this code silently changes to a no-op.
206 initial.SetPosition( Position( 10, 10 ) );
210 Code that is not used (commented out) should be deleted.
211 Rationale: No dead code should be left to confuse other people.
212 Exception: Code that is simply part of an explanation may appear in comments.
218 <H2>Inline member functions <input type="button" value="Hide" onclick="toggleVisibility( this, 'inline_details' );"/></H2>
219 <ARTICLE class="detail" id="inline_details">
222 GCC automatically inlines member functions defined within the class body of C++ programs even if they are not explicitly declared inline.
226 inline float& GetRed() { return mRed; } // inline keyword not needed
227 inline float& GetGreen(){ return mGreen; }
233 float& GetRed() { return mRed; }
234 float& GetGreen(){ return mGreen; }
239 If there are a lot of inlines, they should be in a .inl file.
240 Remember the inline keyword is just a hint to the compiler. Whether
241 a function will be inlined or not is down to the compiler and its flags.
247 <H2>Conversion operators <input type="button" value="Hide" onclick="toggleVisibility( this, 'conversion_details' );"/></H2>
248 <ARTICLE class="detail" id="conversion_details">
251 Don't declare implicit conversion operators in classes. They allow the compiler to trip you up and go from one type to another via the conversion operator unintentionally.
252 Conversion operators are particularly dangerous in conjunction with auto keyword. If conversion is required, make it explicit or better yet, add a getter with a more meaningfull name.
259 // implicit conversion to float
260 operator float() const { return float( val ); }
264 //... and in the program:
270 value = foo; // oops, didn't really want to allow conversion to int but the compiler can do that as float can be assigned to int.
281 // explicit getter for float
282 float AsFloat const { return static_cast<float>( val ); }
286 //... and in the program:
292 si.AsFloat() + 3; // ok: explicitly request the conversion
301 // explicit conversion to int
302 explicit operator int() const { return val; }
306 //... and in the program:
310 SmallInt si = 3; // ok: the SmallInt constructor is not explicit
311 si + 3; // error: implicit is conversion required, but operator int is explicit
312 static_cast<int>(si) + 3; // ok: explicitly request the conversion
323 <H2>Auto keyword <input type="button" value="Hide" onclick="toggleVisibility( this, 'auto_details' );"/></H2>
324 <ARTICLE class="detail" id="auto_details">
327 auto keyword should only be used where it improves the readability of the code and does not lead to ambiguities.
328 never use auto in a line where multiple different types occur as part of expressions like additions, subtracts, multiplies as whe conversion ordering rules are not always obvious.
333 auto actor = Actor::DownCast(GetOwner()); // it is obvious that actor is of type Actor so no need to retype the type
334 auto widthMode = widthMeasureSpec.GetMode(); // it is relatively obvious that Mode is an enumeration with potentially long name so no need to repeat the type, no ambiguity
335 auto childLayout = GetChildAt( i ); // name of the variable is clear enough indication of the type, no ambiguity
336 auto childPosition = childOwner.GetProperty< Dali::Vector3 >( Actor::Property::POSITION ); // getter already contains the type, no need to repeat it
338 for ( auto&& renderTask : mImpl->taskList.GetTasks() ) // iterator type not relevant for the algorithm, code much cleaner with auto
340 renderTask->UpdateState();
347 auto width = layout->GetWidth() - padding.end - padding.start; // not obvious what the final type ends up as multiple type conversions may occur
349 auto size = std::max( LayoutLength(0), specSize - padding ); // not obvious which of the types is preferred by compiler; or what the type of specSize - padding actually is
351 auto minPosition = Vector3( Vector3::ZERO ); // auto does not add any value here
355 Vector3 minPosition; // vector initializes to 0,0,0
359 auto specification = MeasureSpec( GetMeasuredHeight(), MeasureSpec::Mode::EXACTLY ); // no value in typing auto in assignment, much cleaner and less ambiguous to write:
363 MeasureSpec specification( GetMeasuredHeight(), MeasureSpec::Mode::EXACTLY ); // obvious construction of a type with parameters
371 <H1>General design priciples</H1>
373 Here's a few pragmatic programmer guidelines to follow (<A HREF="http://www.codinghorror.com/blog/files/Pragmatic%20Quick%20Reference.htm">Web version</A>)
374 <H3>Details <input type="button" value="Hide" onclick="toggleVisibility( this, 'general_details' );"/></H3>
375 <ARTICLE class="detail" id="general_details">
377 <LI><B>Care About the Software, Care about your API users and end users</B><BR>
378 Why spend your life developing software unless you care about doing it well?
379 Turn off the autopilot and take control. Constantly critique and appraise your work.
380 <LI><B>Don't Live with Broken Windows</B><BR>
381 Fix bad designs, wrong decisions, and poor code when you see them.
382 You can't force change on people. Instead, show them how the future might be and help them participate in creating it.
383 <LI><B>Remember the Big Picture</B><BR>
384 Don't get so engrossed in the details that you forget to check what's happening around you.
385 <LI><B>DRY - Don't Repeat Yourself</B><BR>
386 Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
387 <LI><B>Eliminate Effects Between Unrelated Things</B><BR>
388 Design components that are self-contained. independent, and have a single, well-defined purpose.
389 <LI><B>There Are No Final Decisions</B><BR>
390 No decision is cast in stone. Instead, consider each as being written in the sand at the beach, and plan for change.
391 <LI><B>Fix the Problem, Not the Blame</B><BR>
392 It doesn't really matter whether the bug is your fault or someone else's—it is still your problem, and it still needs to be fixed.
393 <LI><B>You Can't Write Perfect Software</B><BR>
394 Software can't be perfect. Protect your code and users from the inevitable errors.
395 <LI><B>Design with Contracts</B><BR>
396 Use contracts to document and verify that code does no more and no less than it claims to do.
397 <LI><B>Crash Early</B><BR>
398 A dead program normally does a lot less damage than a crippled one.
399 <LI><B>Use Assertions to Prevent the Impossible</B><BR>
400 Assertions validate your assumptions. Use them to protect your code from an uncertain world.
401 <LI><B>Use Exceptions for Exceptional Problems</B><BR>
402 Exceptions can suffer from all the readability and maintainability problems of classic spaghetti code. Reserve exceptions for exceptional things.
403 <LI><B>Minimize Coupling Between Modules</B><BR>
404 Avoid coupling by writing "shy" code and applying the Law of Demeter.
405 <LI><B>Put Abstractions in Code, Details in Metadata</B><BR>
406 Program for the general case, and put the specifics outside the compiled code base.
407 <LI><B>Always Design for Concurrency</B><BR>
408 Allow for concurrency, and you'll design cleaner interfaces with fewer assumptions.
409 <LI><B>Don't Program by Coincidence</B><BR>
410 Rely only on reliable things. Beware of accidental complexity, and don't confuse a happy coincidence with a purposeful plan.
411 <LI><B>Test Your Estimates</B><BR>
412 Mathematical analysis of algorithms doesn't tell you everything. Try timing your code in its target environment.
413 <LI><B>Refactor Early, Refactor Often</B><BR>
414 Just as you might weed and rearrange a garden, rewrite, rework, and re-architect code when it needs it. Fix the root of the problem.
415 <LI><B>Design to Test</B><BR>
416 Start thinking about testing before you write a line of code.
417 <LI><B>Abstractions Live Longer than Details</B><BR>
418 Invest in the abstraction, not the implementation. Abstractions can survive the barrage of changes from different implementations and new technologies.
419 <LI><B>Coding Ain't Done 'Til All the Tests Run</B><BR>
421 <LI><B>Use Saboteurs to Test Your Testing</B><BR>
422 Introduce bugs on purpose in a separate copy of the source to verify that testing will catch them.
423 <LI><B>Find Bugs Once</B><BR>
424 Once a human tester finds a bug, it should be the last time a human tester finds that bug. Automatic tests should check for it from then on.
425 <LI><B>Sign Your Work</B><BR>
426 Craftsmen of an earlier age were proud to sign their work. You should be, too.
431 <H2>Avoid Tight Coupling</H2>
433 Always choose the loosest possible coupling between entities. In C++ the tightest coupling is Friend, second is Inheritance,
434 then Containment and last is Usage through reference, pointer or handle.
435 <H3>Details <input type="button" value="Hide" onclick="toggleVisibility( this, 'coupling_details' );"/></H3>
436 <ARTICLE class="detail" id="coupling_details">
438 <LI>Friend defines a "must-know" about details of implementation, don't use it unless your happy stating that Xxx really <B>must</B> know about Yyy implementation. and Yyy can never change without informing Xxx.
439 <LI>Inheritance defines a "is-a" relationship, don't use it unless you really can naturally say Xxx is-a Yyy. Most of the cases containment through interface is what you
440 <LI>Containment defines a "owns-a" relationship, use it when you have a natural Xxx owns-a Yyy relationship.
442 Most of the time containment through interface and normal usage is what you should go for.
443 Strong ownership always beats sharing through reference counting. Reference counting means "part owns".
444 You would not want to part own anything in real life, so why do that in software? sooner or later it will leak,
448 Two key principles to follow:
449 <H2>Open Closed Principle</H2>
451 Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
452 That is, such an entity can allow its behaviour to be modified without altering its source code. Techniqu
455 <H2>Dependency Inversion Principle</H2>
457 High-level modules should not depend on low-level modules. Both should depend on abstractions.
458 Abstractions should not depend upon details. Details should depend upon abstractions.
461 <P>Thats all folks, if you read this far you are now all equipped to write good code :) !! </P>