C++11 override should now be supported by all of {bots,Chrome,Android,Mozilla}
[platform/upstream/libSkiaSharp.git] / site / dev / contrib / style.md
1 Coding Style Guidelines
2 =======================
3
4 These conventions have evolved over time. Some of the earlier code in both
5 projects doesn’t strictly adhere to the guidelines. However, as the code evolves
6 we hope to make the existing code conform to the guildelines.
7
8 Files
9 -----
10
11 We use .cpp and .h as extensions for c++ source and header files. We use
12 foo_impl.h for headers with inline definitions for class foo.
13
14 Headers that aren’t meant for public consumption should be placed in src
15 directories so that they aren’t in a client’s search path.
16
17 We prefer to minimize includes. If forward declaring a name in a header is
18 sufficient then that is preferred to an include.
19
20 Forward declarations and file includes should be in alphabetical order (but we
21 aren't very strict about it).
22
23 <span id="no-define-before-sktypes"></span>
24 Do not use #if/#ifdef before including "SkTypes.h" (directly or indirectly).
25
26 We use spaces not tabs (4 of them).
27
28 We use Unix style endlines (LF).
29
30 We prefer no trailing whitespace but aren't very strict about it.
31
32 We wrap lines at 100 columns unless it is excessively ugly (use your judgement).
33 The soft line length limit was changed from 80 to 100 columns in June 2012. Thus,
34 most files still adhere to the 80 column limit. It is not necessary or worth
35 significant effort to promote 80 column wrapped files to 100 columns. Please
36 don't willy-nilly insert longer lines in 80 column wrapped files. Either be
37 consistent with the surrounding code or, if you really feel the need, promote
38 the surrounding code to 100 column wrapping.
39
40 Naming
41 ------
42
43 Both projects use a prefix to designate that they are Skia prefix for classes,
44 enums, structs, typedefs etc is Sk. Ganesh’s is Gr. Nested types should not be
45 prefixed.
46
47 <!--?prettify?-->
48 ~~~~
49 class SkClass {
50 public:
51     class HelperClass {
52         ...
53     };
54 };
55 ~~~~
56
57 Data fields in structs, classes, unions begin with lowercase f and are then 
58 camel capped.
59
60 <!--?prettify?-->
61 ~~~~
62 struct GrCar {
63     ...
64     float fMilesDriven;
65     ...
66 };
67 ~~~~
68
69 Globals variables are similar but prefixed with g and camel-capped
70
71 <!--?prettify?-->
72 ~~~~
73 bool gLoggingEnabled
74 Local variables begin lowercases and are camel-capped.
75
76 int herdCats(const Array& cats) {
77     int numCats = cats.count();
78 }
79 ~~~~
80
81 Enum values are prefixed with k and have post fix that consists of an underscore
82 and singular name of the enum name. The enum itself should be singular for
83 exclusive values or plural for a bitfield. If a count is needed it is 
84 k<singular enum name>Count and not be a member of the enum (see example):
85
86 <!--?prettify?-->
87 ~~~~
88 enum SkPancakeType {
89      kBlueberry_PancakeType,
90      kPlain_PancakeType,
91      kChocolateChip_PancakeType,
92     
93      kLast_PancakeType = kChocolateChip_PancakeType
94 };
95
96 static const SkPancakeType kPancakeTypeCount = kLast_PancakeType + 1;
97 ~~~~
98
99 A bitfield:
100
101 <!--?prettify?-->
102 ~~~~
103 enum SkSausageIngredientBits {
104     kFennel_SuasageIngredientBit = 0x1,
105     kBeef_SausageIngredientBit   = 0x2
106 };
107 ~~~~
108
109 or:
110
111 <!--?prettify?-->
112 ~~~~
113 enum SkMatrixFlags {
114     kTranslate_MatrixFlag = 0x1,
115     kRotate_MatrixFlag    = 0x2
116 };
117 ~~~~
118
119 Exception: anonymous enums can be used to declare integral constants, e.g.:
120
121 <!--?prettify?-->
122 ~~~~
123 enum { kFavoriteNumber = 7 };
124 ~~~~
125
126 Macros are all caps with underscores between words. Macros that have greater
127 than file scope should be prefixed SK or GR.
128
129 Static non-class functions in implementation files are lower case with
130 underscores separating words:
131
132 <!--?prettify?-->
133 ~~~~
134 static inline bool tastes_like_chicken(Food food) {
135     return kIceCream_Food != food;
136 }
137 ~~~~
138
139 Externed functions or static class functions are camel-capped with an initial cap:
140
141 <!--?prettify?-->
142 ~~~~
143 bool SkIsOdd(int n);
144
145 class SkFoo {
146 public:
147     static int FooInstanceCount();
148 };
149 ~~~~
150
151 Macros
152 ------
153
154 Ganesh macros that are GL-specific should be prefixed GR_GL.
155
156 <!--?prettify?-->
157 ~~~~
158 #define GR_GL_TEXTURE0 0xdeadbeef
159 ~~~~
160
161 Ganesh prefers that macros are always defined and the use of #if MACRO rather than 
162 #ifdef MACRO.
163
164 <!--?prettify?-->
165 ~~~~
166 #define GR_GO_SLOWER 0
167 ...
168 #if GR_GO_SLOWER
169     Sleep(1000);
170 #endif
171 ~~~~
172
173 Skia tends to use #ifdef SK_MACRO for boolean flags.
174
175 Braces
176 ------
177
178 Open braces don’t get a newline. “else” and “else if” appear on same line as
179 opening and closing braces unless preprocessor conditional compilation
180 interferes. Braces are always used with if, else, while, for, and do.
181
182 <!--?prettify?-->
183 ~~~~
184 if (...) {
185     oneOrManyLines;
186 }
187
188 if (...) {
189     oneOrManyLines;
190 } else if (...) {
191     oneOrManyLines;
192 } else {
193     oneOrManyLines;
194 }
195
196 for (...) {
197     oneOrManyLines;
198 }
199
200 while (...) {
201     oneOrManyLines;
202 }
203
204 void function(...) {
205     oneOrManyLines;
206 }
207
208 if (!error) {
209     proceed_as_usual();
210 }
211 #if HANDLE_ERROR
212 else {
213     freak_out();
214 }
215 #endif
216 ~~~~
217
218 Flow Control
219 ------------
220
221 There is a space between flow control words and parentheses and between 
222 parentheses and braces:
223
224 <!--?prettify?-->
225 ~~~~
226 while (...) {
227 }
228
229 do {
230 } while(...);
231
232 switch (...) {
233 ...
234 }
235 ~~~~
236
237 Cases and default in switch statements are indented from the switch.
238
239 <!--?prettify?-->
240 ~~~~
241 switch (color) {
242     case kBlue:
243         ...
244         break;
245     case kGreen:
246         ... 
247         break;
248     ...
249     default:
250        ...
251        break;
252 }
253 ~~~~
254
255 Fallthrough from one case to the next is commented unless it is trivial:
256
257 <!--?prettify?-->
258 ~~~~
259 switch (recipe) {
260     ...
261     case kCheeseOmelette_Recipe:
262         ingredients |= kCheese_Ingredient;
263         // fallthrough
264     case kPlainOmelette_Recipe:
265         ingredients |= (kEgg_Ingredient | kMilk_Ingredient);
266         break;
267     ...
268 }
269 ~~~~
270
271 When a block is needed to declare variables within a case follow this pattern:
272
273 <!--?prettify?-->
274 ~~~~
275 switch (filter) {
276     ...
277     case kGaussian_Filter: {
278         Bitmap srcCopy = src->makeCopy(); 
279         ...
280         break;
281     }
282     ...
283 };
284 ~~~~
285
286 Classes
287 -------
288
289 Unless there is a need for forward declaring something, class declarations
290 should be ordered public, protected, private. Each should be preceded by a
291 newline. Within each visibility section (public, private), fields should not be
292 intermixed with methods.
293
294 <!--?prettify?-->
295 ~~~~
296 class SkFoo {
297
298 public:
299     ...
300
301 protected:
302     ...        
303
304 private:
305     SkBar fBar;
306     ...
307
308     void barHelper(...);
309     ...
310 };
311 ~~~~
312
313 Subclasses should have a private typedef of their super class called INHERITED:
314
315 <!--?prettify?-->
316 ~~~~
317 class GrDillPickle : public GrPickle {
318     ...
319 private:
320     typedef GrPickle INHERITED;
321 };
322 ~~~~
323
324 Virtual functions that are overridden in derived classes should use override
325 (and not the override keyword). The virtual keyword can be omitted.
326
327 <!--?prettify?-->
328 ~~~~
329 void myVirtual() override {
330 }
331 ~~~~
332
333 This should be the last element of their private section, and all references to 
334 base-class implementations of a virtual function should be explicitly qualified:
335
336 <!--?prettify?-->
337 ~~~~
338 void myVirtual() override {
339     ...
340     this->INHERITED::myVirtual();
341     ...
342 }
343 ~~~~
344
345 As in the above example, derived classes that redefine virtual functions should
346 use override to note that explicitly.
347
348 Constructor initializers should be one per line, indented, with punctuation
349 placed before the initializer. This is a fairly new rule so much of the existing
350 code is non-conforming. Please fix as you go!
351
352 <!--?prettify?-->
353 ~~~~
354 GrDillPickle::GrDillPickle()
355     : GrPickle()
356     , fSize(kDefaultPickleSize) {
357     ...
358 }
359 ~~~~
360
361 Constructors that take one argument should almost always be explicit, with 
362 exceptions made only for the (rare) automatic compatibility class.
363
364 <!--?prettify?-->
365 ~~~~
366 class Foo {
367     explicit Foo(int x);  // Good.
368     Foo(float y);         // Spooky implicit conversion from float to Foo.  No no no!
369     ...
370 };
371 ~~~~
372
373 Method calls within method calls should be prefixed with dereference of the 
374 'this' pointer. For example:
375
376 <!--?prettify?-->
377 ~~~~
378 this->method();
379 Memory Management
380 ~~~~
381
382 All memory allocation should be routed through SkNEW and its variants. These are
383 #defined in SkPostConfig.h, but the correct way to get access to the config
384 system is to #include SkTypes.h, which will allow external users of the library
385 to provide a custom memory manager or other adaptations.
386
387 <!--?prettify?-->
388 ~~~~
389 SkNEW(type_name)
390 SkNEW_ARGS(type_name, args)
391 SkNEW_ARRAY(type_name, count)
392 SkNEW_PLACEMENT(buf, type_name)
393 SkNEW_PLACEMENT_ARGS(buf, type_name, args)
394 SkDELETE(obj)
395 SkDELETE_ARRAY(array)
396 ~~~~
397
398 Comparisons
399 -----------
400
401 We prefer that equality operators between lvalues and rvalues place the lvalue 
402 on the right:
403
404 <!--?prettify?-->
405 ~~~~
406 if (7 == luckyNumber) {
407     ...
408 }
409 ~~~~
410
411 However, inequality operators need not follow this rule:
412
413 <!--?prettify?-->
414 ~~~~
415 if (count > 0) {
416     ...
417 }
418 ~~~~
419
420 Comments
421
422 We use doxygen-style comments.
423
424 For grouping or separators in an implementation file we use 80 slashes
425
426 <!--?prettify?-->
427 ~~~~
428 void SkClassA::foo() {
429     ...
430 }
431
432 ////////////////////////////////////////////////////////////////
433
434 void SkClassB::bar() {
435     ...
436 }
437 ~~~~
438
439 Integer Types
440 -------------
441
442 We follow the Google C++ guide for ints and are slowly making older code conform to this
443
444 (http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Integer_Types)
445
446 Summary: Use int unless you have need a guarantee on the bit count, then use
447 stdint.h types (int32_t, etc). Assert that counts, etc are not negative instead
448 of using unsigned. Bitfields use uint32_t unless they have to be made shorter
449 for packing or performance reasons.
450
451 NULL, 0
452 -------
453
454 Use NULL for pointers, 0 for ints. We prefer explicit NULL comparisons when
455 checking for NULL pointers (as documentation):
456
457 <!--?prettify?-->
458 ~~~~
459 if (NULL == x) {  // slightly preferred over if (!x)
460    ...
461 }
462 ~~~~
463
464 When checking non-NULL pointers explicit comparisons are not required because it
465 reads like a double negative:
466
467 <!--?prettify?-->
468 ~~~~
469 if (x) {  // slightly preferred over if (NULL != x)
470    ...
471 }
472 ~~~~
473
474 Returning structs
475 -----------------
476
477 If the desired behavior is for a function to return a struct, we prefer using a
478 struct as an output parameter
479
480 <!--?prettify?-->
481 ~~~~
482 void modify_foo(SkFoo* foo) {
483     // Modify foo
484 }
485 ~~~~
486
487 Then the function can be called as followed:
488
489 <!--?prettify?-->
490 ~~~~
491 SkFoo foo;
492 modify_foo(&foo);
493 ~~~~
494
495 This way, if return value optimization cannot be used there is no performance
496 hit. It also means that modify_foo can actually return a boolean for whether the
497 call was successful. In this case, initialization of foo can potentially be
498 skipped on failure (assuming the constructor for SkFoo does no initialization).
499
500 <!--?prettify?-->
501 ~~~~
502 bool modify_foo(SkFoo* foo) {
503     if (some_condition) {
504         // Modify foo
505         return true;
506     }
507     // Leave foo unmodified
508     return false;
509 }
510 ~~~~
511
512 Function Parameters
513 -------------------
514
515 Mandatory constant object parameters are passed to functions as const references
516 if they are not retained by the receiving function. Optional constant object
517 parameters are passed to functions as const pointers. Objects that the called
518 function will retain, either directly or indirectly, are passed as pointers.
519 Variable (i.e. mutable) object parameters are passed to functions as pointers.
520
521 <!--?prettify?-->
522 ~~~~
523 // src and paint are optional
524 void SkCanvas::drawBitmapRect(const SkBitmap& bitmap, const SkIRect* src, 
525                              const SkRect& dst, const SkPaint* paint = NULL);
526 // metrics is mutable (it is changed by the method)
527 SkScalar SkPaint::getFontMetrics(FontMetric* metrics, SkScalar scale) const;
528 // A reference to foo is retained by SkContainer
529 void SkContainer::insert(const SkFoo* foo);
530 ~~~~
531
532 If function arguments or parameters do not all fit on one line, they may be
533 lined up with the first parameter on the same line
534
535 <!--?prettify?-->
536 ~~~~
537 void drawBitmapRect(const SkBitmap& bitmap, const SkRect& dst,
538                     const SkPaint* paint = NULL) {
539     this->drawBitmapRectToRect(bitmap, NULL, dst, paint,
540                                kNone_DrawBitmapRectFlag);
541 }
542 ~~~~
543
544 or placed on the next line indented eight spaces
545
546 <!--?prettify?-->
547 ~~~~
548 void drawBitmapRect(
549         const SkBitmap& bitmap, const SkRect& dst,
550         const SkPaint* paint = NULL) {
551     this->drawBitmapRectToRect(
552             bitmap, NULL, dst, paint, kNone_DrawBitmapRectFlag);
553 }
554 ~~~~
555
556 Python
557 ------
558
559 Python code follows the [Google Python Style Guide](http://google-styleguide.googlecode.com/svn/trunk/pyguide.html).
560