Removed memcpy() from uniform write
[platform/core/uifw/dali-core.git] / docs / coding-convention.html
1 <HTML>
2 <HEAD>
3 <TITLE>Dali C++ Coding Conventions</TITLE>
4 <!--
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
8 -->
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; }
13 </style>
14
15 <script type="text/javascript">
16 function toggleVisibility( button, obj )
17 {
18   // must have button and object
19   if( !button || !obj )
20     return;
21   var e=document.getElementById( obj );
22   if( !e )
23     return;
24
25   // initially display property seems to be empty, then none
26   if( e.style.display == "" || e.style.display == "none" )
27   {
28     // paragraph shown
29     button.value="Hide";
30     e.style.display="block";
31   }
32   else
33   {
34     // paragraph hidden
35     button.value="Show";
36     e.style.display="none";
37   }
38 }
39 </script>
40
41 </HEAD>
42 <BODY>
43
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">
47       <SUMMARY>
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>
56       </SUMMARY>
57       <CODE class="good">
58   X* ptr = static_cast&#x3C;X*&#x3E;( y_ptr ); // ok, compiler checks whether types are compatible
59       </CODE>
60       <CODE class="bad">
61   (Foo*) ptr; // bad! C-cast is not guaranteed to check and never complains
62       </CODE>
63     </ARTICLE>
64
65 <H1>Classes</H1>
66   <SUMMARY>
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.
71   </SUMMARY>
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">
74       <SUMMARY>
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.
78       </SUMMARY>
79       <P>
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.
85       </P>
86       <CODE class="good">
87   class X
88   {
89     X();                      // default constructor
90     X( const X& );            // copy constructor
91     X& operator=( const X& ); // copy assignment operator
92     ~X();                     // destructor
93   };
94
95   class X
96   {
97     X();                                // default constructor
98     ~X();                               // destructor
99     X( const X& ) = delete;             // copy constructor not allowed
100     X& operator=( const X& ); = delete; // copy assignment operator not allowed
101   };
102       </CODE>
103     </ARTICLE>
104   <H2>Class types <input type="button" value="Hide" onclick="toggleVisibility( this, 'class_types_details' );"/></H2>
105     <ARTICLE class="detail" id="class_types_details">
106       <SUMMARY>
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.
110       </SUMMARY>
111       <P>
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.
114       </P>
115       <P>
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.
119       </P>
120     </ARTICLE>
121   <H2>Access Rights <input type="button" value="Hide" onclick="toggleVisibility( this, 'access_details' );"/></H2>
122     <ARTICLE class="detail" id="access_details">
123       <P>
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.
127       </P>
128       <P>
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.
134       </P>
135     </ARTICLE>
136   <H2>Constructors <input type="button" value="Hide" onclick="toggleVisibility( this, 'constructor_details' );"/></H2>
137     <ARTICLE class="detail" id="constructor_details">
138       <P>
139         Virtual function calls are not allowed from constructor
140         Rationale: Virtual functions are resolved statically (not dynamically) in constructor
141       </P>
142       <P>
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.
148       </P>
149       <P>
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.
152       </P>
153       <P>
154         Declare all single argument constructors as explicit thus preventing their use as implicit type convertors.
155         <CODE class="good">
156   class C
157   {
158   public:
159     explicit C( int );         // good, explicit
160     C( int, int );             // ok more than one non-default argument
161   };
162         </CODE>
163         <CODE class="bad">
164   class C
165   {
166   public:
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
170   };
171         </CODE>
172       </P>
173     </ARTICLE>
174   <H2>Destructor <input type="button" value="Hide" onclick="toggleVisibility( this, 'destructor_details' );"/></H2>
175     <ARTICLE class="detail" id="destructor_details">
176       <P>
177         All classes should define a destructor, either:
178         <UL>
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
182         </UL>
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.
185       </P>
186       <P>
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
189       </P>
190       <P>
191         All resources acquired by a class shall be released by the class's destructor.
192       </P>
193       <P>
194         Destructor is not allowed to throw an exception, avoid doing complicated things in destructor.
195       </P>
196     </ARTICLE>
197   <H2>Methods <input type="button" value="Hide" onclick="toggleVisibility( this, 'method_details' );"/></H2>
198     <ARTICLE class="detail" id="method_details">
199       <P>
200         Don't shortcut, like use the returned reference of getter to assign a new value. If a Setter is missing, add it!
201         <CODE class="bad">
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.
204         </CODE>
205         <CODE class="good">
206   initial.SetPosition( Position( 10, 10 ) );
207         </CODE>
208       </P>
209       <P>
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.
213       </P>
214       <P>
215       </P>
216     </ARTICLE>
217
218   <H2>Inline member functions <input type="button" value="Hide" onclick="toggleVisibility( this, 'inline_details' );"/></H2>
219     <ARTICLE class="detail" id="inline_details">
220       <P>
221
222         GCC automatically inlines member functions defined within the class body of C++ programs even if they are not explicitly declared inline.
223         <CODE class="bad">
224   class Color
225   {
226     inline float& GetRed()  { return mRed;   } // inline keyword not needed
227     inline float& GetGreen(){ return mGreen; }
228   };
229         </CODE>
230         <CODE class="good">
231   class Color
232   {
233     float& GetRed()   { return mRed;   }
234     float& GetGreen(){ return mGreen; }
235   };
236         </CODE>
237       </P>
238       <P>
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.
242       </P>
243       <P>
244       </P>
245     </ARTICLE>
246
247   <H2>Conversion operators <input type="button" value="Hide" onclick="toggleVisibility( this, 'conversion_details' );"/></H2>
248     <ARTICLE class="detail" id="conversion_details">
249       <P>
250
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.
253         <CODE class="bad">
254
255   // Bad:
256   class SmallInt
257   {
258   public:
259     // implicit conversion to float
260     operator float() const { return float( val ); }
261   private:
262     int val;
263   };
264   //... and in the program:
265
266   int main( void )
267   {
268     int value;
269     SmallValue foo;
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.
271
272     return 0;
273   }
274         </CODE>
275         <CODE class="good">
276
277   // Good:
278   class SmallInt
279   {
280   public:
281     // explicit getter for float
282     float AsFloat const { return static_cast&#x3C;float&#x3E;( val ); }
283   private:
284     int val;
285   };
286   //... and in the program:
287
288   int main( void )
289   {
290     int value;
291     SmallValue foo;
292     si.AsFloat() + 3; // ok: explicitly request the conversion
293
294     return 0;
295   }
296
297   // Good:
298   class SmallInt
299   {
300   public:
301     // explicit conversion to int
302     explicit operator int() const { return val; }
303   private:
304     int val;
305   };
306   //... and in the program:
307
308   int main()
309   {
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&#x3C;int&#x3E;(si) + 3; // ok: explicitly request the conversion
313
314     return 0;
315   }
316
317         </CODE>
318       </P>
319       <P>
320       </P>
321     </ARTICLE>
322
323   <H2>Auto keyword <input type="button" value="Hide" onclick="toggleVisibility( this, 'auto_details' );"/></H2>
324     <ARTICLE class="detail" id="auto_details">
325       <P>
326
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 the conversion ordering rules are not always obvious.
329
330         <CODE class="good">
331
332   // Good:
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&#x3C; Dali::Vector3 &#x3E;( Actor::Property::POSITION ); // getter already contains the type, no need to repeat it
337
338   for ( auto&& renderTask : mImpl->taskList.GetTasks() ) // iterator type not relevant for the algorithm, code much cleaner with auto
339   {
340     renderTask->UpdateState();
341   }
342
343         </CODE>
344         <CODE class="bad">
345
346   // Bad:
347   auto width = layout->GetWidth() - padding.end - padding.start; // not obvious what the final type ends up as multiple type conversions may occur
348
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
350
351   auto minPosition = Vector3( Vector3::ZERO ); // auto does not add any value here
352         </CODE>
353         <CODE class="good">
354   // Good:
355   Vector3 minPosition; // vector initializes to 0,0,0
356         </CODE>
357         <CODE class="bad">
358   // Bad:
359   auto specification = MeasureSpec( GetMeasuredHeight(), MeasureSpec::Mode::EXACTLY ); // no value in typing auto in assignment, much cleaner and less ambiguous to write:
360         </CODE>
361         <CODE class="good">
362   // Good:
363   MeasureSpec specification( GetMeasuredHeight(), MeasureSpec::Mode::EXACTLY ); // obvious construction of a type with parameters
364         </CODE>
365
366       </P>
367       <P>
368       </P>
369     </ARTICLE>
370
371   <H2>Class Inheritance <input type="button" value="Hide" onclick="toggleVisibility( this, 'class_inheritance' );"/></H2>
372     <H3>Overriding</H3>
373     <ARTICLE class="detail" id="class_inheritance">
374       <P>
375
376         When using inheritance, any methods in the base class that can be overridden MUST be marked as <b>virtual</b>.
377         In deriving classes, when a virtual method is overridden, then only use the <b>override</b> keyword.
378         If a method should not be overridden further, then use the <b>final</b> keyword alone.
379
380         <CODE class="good">
381
382   // Good:
383   class Base
384   {
385   public:
386     virtual void Print() const;
387     virtual void SetPrintSpeed( float speed );
388   };
389
390   class Derived : public Base
391   {
392   public:
393     void Print() const override;
394     void SetPrintSpeed( float speed ) final;
395   };
396         </CODE>
397       </P>
398       <P>
399         If a class should not be overridden then use the <b>final</b> keyword on the class itself.
400         This should also be done for a derived class that should not to be overridden further as well.
401         Overridden methods within that class can be marked as <b>final</b> or <b>override</b>.
402
403         <CODE class="good">
404
405   class Derived final : public Base
406   {
407   public:
408     void Print() const override;
409     void SetPrintSpeed( float speed ) final;
410   };
411         </CODE>
412       </P>
413     <H3>Overloading</H3>
414       <P>
415         Overloading of Base class methods SHOULD be avoided but if it's required, then use the <b>using</b> keyword.
416
417         <CODE class="good">
418
419   class Derived : public Base
420   {
421   public:
422     void Print( float number ) const; // overloaded member
423     using Base::Print; // Make the Base class' Print method visible here as well.
424   };
425         </CODE>
426       </P>
427       <P>
428         If we do not add the using line, then we can only use the overloaded Print method for a Derived object (unless we cast to the Base class).
429         Attempting to use the base class' Print() method on a Derived object would result in a compilation error.
430       </P>
431       <P>
432       </P>
433     </ARTICLE>
434
435 <H1>General design priciples</H1>
436   <P>
437     Here's a few pragmatic programmer guidelines to follow (<A HREF="http://www.codinghorror.com/blog/files/Pragmatic%20Quick%20Reference.htm">Web version</A>)
438     <H3>Details <input type="button" value="Hide" onclick="toggleVisibility( this, 'general_details' );"/></H3>
439     <ARTICLE class="detail" id="general_details">
440       <UL>
441       <LI><B>Care About the Software, Care about your API users and end users</B><BR>
442             Why spend your life developing software unless you care about doing it well?
443             Turn off the autopilot and take control. Constantly critique and appraise your work.
444       <LI><B>Don't Live with Broken Windows</B><BR>
445             Fix bad designs, wrong decisions, and poor code when you see them.
446             You can't force change on people. Instead, show them how the future might be and help them participate in creating it.
447       <LI><B>Remember the Big Picture</B><BR>
448             Don't get so engrossed in the details that you forget to check what's happening around you.
449       <LI><B>DRY - Don't Repeat Yourself</B><BR>
450             Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
451       <LI><B>Eliminate Effects Between Unrelated Things</B><BR>
452             Design components that are self-contained. independent, and have a single, well-defined purpose.
453       <LI><B>There Are No Final Decisions</B><BR>
454             No decision is cast in stone. Instead, consider each as being written in the sand at the beach, and plan for change.
455       <LI><B>Fix the Problem, Not the Blame</B><BR>
456             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.
457       <LI><B>You Can't Write Perfect Software</B><BR>
458             Software can't be perfect. Protect your code and users from the inevitable errors.
459       <LI><B>Design with Contracts</B><BR>
460             Use contracts to document and verify that code does no more and no less than it claims to do.
461       <LI><B>Crash Early</B><BR>
462             A dead program normally does a lot less damage than a crippled one.
463       <LI><B>Use Assertions to Prevent the Impossible</B><BR>
464             Assertions validate your assumptions. Use them to protect your code from an uncertain world.
465       <LI><B>Use Exceptions for Exceptional Problems</B><BR>
466             Exceptions can suffer from all the readability and maintainability problems of classic spaghetti code. Reserve exceptions for exceptional things.
467       <LI><B>Minimize Coupling Between Modules</B><BR>
468             Avoid coupling by writing "shy" code and applying the Law of Demeter.
469       <LI><B>Put Abstractions in Code, Details in Metadata</B><BR>
470             Program for the general case, and put the specifics outside the compiled code base.
471       <LI><B>Always Design for Concurrency</B><BR>
472             Allow for concurrency, and you'll design cleaner interfaces with fewer assumptions.
473       <LI><B>Don't Program by Coincidence</B><BR>
474             Rely only on reliable things. Beware of accidental complexity, and don't confuse a happy coincidence with a purposeful plan.
475       <LI><B>Test Your Estimates</B><BR>
476             Mathematical analysis of algorithms doesn't tell you everything. Try timing your code in its target environment.
477       <LI><B>Refactor Early, Refactor Often</B><BR>
478             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.
479       <LI><B>Design to Test</B><BR>
480             Start thinking about testing before you write a line of code.
481       <LI><B>Abstractions Live Longer than Details</B><BR>
482             Invest in the abstraction, not the implementation. Abstractions can survive the barrage of changes from different implementations and new technologies.
483       <LI><B>Coding Ain't Done 'Til All the Tests Run</B><BR>
484             'Nuff said.
485       <LI><B>Use Saboteurs to Test Your Testing</B><BR>
486             Introduce bugs on purpose in a separate copy of the source to verify that testing will catch them.
487       <LI><B>Find Bugs Once</B><BR>
488             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.
489       <LI><B>Sign Your Work</B><BR>
490             Craftsmen of an earlier age were proud to sign their work. You should be, too.
491       </UL>
492     </ARTICLE>
493   </P>
494
495   <H2>Avoid Tight Coupling</H2>
496     <P>
497       Always choose the loosest possible coupling between entities. In C++ the tightest coupling is Friend, second is Inheritance,
498       then Containment and last is Usage through reference, pointer or handle.
499     <H3>Details <input type="button" value="Hide" onclick="toggleVisibility( this, 'coupling_details' );"/></H3>
500     <ARTICLE class="detail" id="coupling_details">
501       <UL>
502         <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.
503         <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
504         <LI>Containment defines a "owns-a" relationship, use it when you have a natural Xxx owns-a Yyy relationship.
505       </UL>
506       Most of the time containment through interface and normal usage is what you should go for.
507       Strong ownership always beats sharing through reference counting. Reference counting means "part owns".
508       You would not want to part own anything in real life, so why do that in software? sooner or later it will leak,
509     </ARTICLE>
510     </P>
511
512   Two key principles to follow:
513   <H2>Open Closed Principle</H2>
514     <P>
515       Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
516       That is, such an entity can allow its behaviour to be modified without altering its source code. Techniqu
517     </P>
518
519   <H2>Dependency Inversion Principle</H2>
520     <P>
521       High-level modules should not depend on low-level modules. Both should depend on abstractions.
522       Abstractions should not depend upon details. Details should depend upon abstractions.
523     </P>
524
525   <P>Thats all folks, if you read this far you are now all equipped to write good code :) !! </P>
526
527 </BODY>
528 </HTML>