Source

dbsdev / docs / coding_style_cpp.html

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
<p><link href="markdown.css" rel="stylesheet"></link></p>

<h1>Coding Style -- C++</h1>

<h2>Contents</h2>

<ol>
<li>Introduction
<ul>
<li>A common style is good</li>
<li>Some choices are arbitrary</li>
<li>Some things don't matter</li>
<li>Avoid revision wars</li>
<li>Style exceptions are allowed</li>
</ul></li>
<li>Naming
<ul>
<li>Naming is important</li>
<li>Names should provide all necessary information, nothing more</li>
<li>A bigger scope warrants a more descriptive name</li>
<li>Do not use abbreviations in names</li>
<li>Name classes <code>LikeThis</code></li>
<li>Name functions and variables <code>likeThis()</code></li>
<li>Name member variables <code>_likeThis</code></li>
<li>Name macros <code>LIKE_THIS</code></li>
<li>Name namespaces <code>like_this</code></li>
<li>Name enums <code>LikeThis</code>, and enum values <code>LIKE_THIS</code></li>
<li>Name files <code>like_this.cpp</code></li>
<li>Order <code>class</code> sections as follows</li>
<li>Standard functions</li>
<li>Use sensible names</li>
</ul></li>
<li>Braces
<ul>
<li>The bracing styles and when to use them</li>
<li>Use braces to increase readability in nested scopes</li>
<li>Try to fit matching braces on a single screen</li>
<li>Use <code>continue</code>, <code>break</code> or even <code>goto</code> (!) to avoid deep nesting</li>
</ul></li>
<li>Indentation and Spacing
<ul>
<li>Use four spaces of indentation</li>
<li>Think about evaluation order when placing spaces</li>
<li>Indent <code>#if</code> statements</li>
<li>Do not indent the entire file</li>
<li>Make lines reasonably long</li>
</ul></li>
<li>Comments
<ul>
<li>Use <code>//</code> for descriptive comments <code>/*</code> for disabling code</li>
<li>Do not leave disabled code in the source</li>
<li>Put interface documentation in the .h file</li>
<li>Use Doxygen syntax for interface documentation</li>
<li>Use comments as hints to the reader</li>
<li>Avoid boilerplate comments</li>
<li>Don't put high level documentation in source code comments</li>
<li>Comment a file like this</li>
<li>Comment a class like this</li>
<li>Comment a function like this</li>
</ul></li>
<li>Language usage
<ul>
<li>Use precision specification</li>
<li>Use <code>const</code> as much as possible</li>
<li>Ordering of class variables and methods should be as follows</li>
<li>Always make class methods <code>const</code> when they do not modify any class variables</li>
<li>Function overloading should be avoided in most cases</li>
</ul></li>
<li>Design and Implementation Issues
<ul>
<li>Optimize wisely</li>
</ul></li>
<li>Miscellaneous
<ul>
<li>Use <code>#pragma once</code> to avoid multiple header inclusion</li>
</ul></li>
</ol>

<h2>1. Introduction</h2>

<h3>1.1 A common style is good</h3>

<p>A common coding style is useful. It makes it easier to communicate, and it makes the code easier to read.</p>

<h3>1.2 Some choices are arbitrary</h3>

<p>This guide is not the Holy Bible. <br>
Some of the style choices described in this manual are (at least according to me) very well motivated, other are just arbitrary choices. Sometimes there is no reason to pick one particular style over another, but it is still useful to use a consistent style.</p>

<h3>1.3 Some things don't matter</h3>

<p>The purpose of this style guide is not to cover every possible situation. If something is not covered by this guide it is probably something that doesn't matter that much and you are free to use whatever style you are most accustomed to. If you think something should be in the guide, just bring it up to discussion.</p>

<h3>1.4 Avoid revision wars</h3>

<p>If you see something that obviously does not follow the standard in a source file you should feel free to change it. <br>
If you see something that perhaps does not follow the standard, but you are not sure, it is better to leave it. <br>
There is not much point in going over the entire codebase looking for style violations. Such nitpicking is not very productive. Instead, just fix the style violations in code you are working on anyway. <br>
Avoid changing the style back and forth in the same piece of code. If you cannot agree on the style, talk about it instead of having a "cold war" in the codebase.</p>

<p>If you disagree strongly with one of the rules in this style guide, you should propose a change to the rule rather than silently rebel.</p>

<h3>1.5 Style exceptions are allowed</h3>

<p>Again this guide is not the Holy Bible. <br>
You can decide to break a rule, but <strong>only</strong> if this brings to a clearer code, depending on the context.</p>

<h2>2. Naming</h2>

<h3>2.1 Naming is important</h3>

<p>Naming is a fundamental part of programming. The ease-of-use and "feeling" of an API depends a lot on having good names.</p>

<p>Furthermore, names are harder to changes than implementations. This is especially true for names that are exported "outside" the executable itself, such as names for script functions and parameters in configuration files. For this reason, some care should be taken when selecting a name.</p>

<h3>2.2 Names should provide all necessary information, nothing more</h3>

<p>A name should provide all the necessary information to understand what a function or variable is doing but no more than that. I.e., it should not contain redundant information or information that is easily understood from the context (such as the class name).</p>

<pre><code>// BAD: Name provides too little information

char *pstoc(char *);
float x;
void Image::draw(float, float);

// BAD: Name provides too much information

char *convert_string_in_pascal_string_format_to_c_string_format(char *);
float the_speed;
void Image::draw_image_at(float, float);

// GOOD: Just the right amount

char *pascal_string_to_c(char *s);
float speed;
void Image::draw_at(float x, float y);
</code></pre>

<p>If you cannot come up with a good name for something -- think harder and consult your colleagues. Never use a name that you know is bad.</p>

<pre><code>// BAD:

// What is link2? How it is different from link?
void link();
void link2();

// These names don't mean anything.
Stuff the_thing;
</code></pre>

<h3>2.3 A bigger scope warrants a more descriptive name</h3>

<p>The more visible a variable is (the larger scope it has) the more descriptive its name needs to be, because less information is provided by the context.</p>

<p>Consider the number of players in a network game. In a small local loop, it is fine to call the variable <code>n</code> because there is not much to confuse it with, and the context immediately shows where the variable is coming from.</p>

<pre><code>int n = num_players();
for (int i=0; i&lt;n; ++i)
   ...
</code></pre>

<p>If it is a function in the network class we need to be more verbose, because n could mean any number of things in that context.</p>

<pre><code>int Network::num_players()
</code></pre>

<p>If it is a global variable, we must be even more verbose, because we no longer have a Network class context that tells us the variable has something to do with the network:</p>

<pre><code>int _num_players_in_network_game;
</code></pre>

<p>Note</p>

<p>Public global variables should be avoided. If you <em>really</em> need a global variable, you should hide it behind a function interface (e.g., console_server::get()). This reduces the temptation of misusing the variable.</p>

<h3>2.4 Do not use abbreviations in names</h3>

<p>There are two problems with abbreviations in names:
* It gets harder to understand what the name means. This is especially the case with extreme and non-sensical abbreviations like wbs2mc.
* Once you start to mix abbreviated and non-abbreviated names, it becomes hard to remember which names where abbreviated and how. It is not hard to understand that world<em>pos means world</em>position. But it can be hard to remember whether the function was called world<em>pos or world</em>position or something else. Never using abbreviation makes it much easier to guess what a function should be called.</p>

<p>The general rule is "do not use any abbreviations at all". <br>
The only allowed exception is <code>num_</code> which means number of, e.g. <code>num_players()</code> instead of <code>number_of_players()</code>.</p>

<p>Note that the rule against abbreviations <strong>only applies to exported symbols</strong>. A local variable can very well be called pos or p.</p>

<h3>2.5 Name classes <code>LikeThis</code></h3>

<p>It is good to use a different standard for classes than variables, because it means that we can give temporary variables of a class good names:</p>

<pre><code>Circle circle;
</code></pre>

<p>If the class was called circle, the variable would have to be called something horrible like <code>a_circle</code> or <code>the_circle</code> or <code>tmp</code>.</p>

<h3>2.6 Name functions and variables <code>likeThis()</code></h3>

<p>Function and variables start with a lower case letter, and use mixed-case to separate words.</p>

<pre><code>// BAD: too similar to class definition
Circle &amp;SmallCircle;
float Radius();
// BAD: lowercases should be used for C or external API support
Circle &amp;small_circle;

// GOOD: 
Circle &amp;circle
int radius();
</code></pre>

<p>Do not use any kind of Hungarian notation when naming variables and functions.</p>

<h3>2.7 Name member variables <code>_likeThis</code></h3>

<p>Being able to quickly distinguish member variables from local variables is good for readability... and it also allows us to use the most natural syntax for getter and setter methods:</p>

<pre><code>Circle &amp;circle() {return _circle;}
void setCircle(Circle &amp;circle) {_circle = circle;}
</code></pre>

<p>A single underscore is used as a prefix, because a prefix with letters in it (like <code>m_</code>) makes the code harder to read.</p>

<pre><code>This _sentence can _be _easily read _even though _it _has _extra underscores.
But m_throw in m_some letters m_and it m_is m_not so m_easy m_anymore, m_okay.
</code></pre>

<p>Also, using '_' makes the member variables stand out more, since there could be other variables starting with 'm'.</p>

<h3>2.8 Name macros <code>LIKE_THIS</code></h3>

<p>It is good to have <code>#define</code> macro names really standing out, since macros can be devious traps when it comes to understanding the code. (Like when Microsoft redefines GetText to GetTextA.)</p>

<h3>2.9 Name namespaces <code>like_this</code></h3>

<p>This is the most readable syntax, so we prefer this when we don't have any reason to do otherwise.
Prefer single-word names.</p>

<h2>2.10 Name enums <code>LikeThis</code>, and enum values <code>LIKE_THIS</code></h2>

<p>Enums are types, just as classes and structs and should follow the same naming convention.</p>

<p>Enum values have big scope (either global scope or enclosing class scope). In many cases enum values are used in the same way as <code>#define</code>s of integer constants and as a user of an API you don't care if a constant is implemented with an enum or with a a macro.</p>

<pre><code>#define ALIGN_LEFT = 0
enum {ALIGN_LEFT = 0};
</code></pre>

<p>Since enum values have almost as big scope as macros and in many cases are used in the same way, we use the same naming convention as for macros:</p>

<pre><code>enum Align {ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTER};
</code></pre>

<p>Note that the prefix ALIGN_ on the enum values is needed, since the enum value scope is big.</p>

<p>If the enum is used to collect a very long (<strong>very</strong> long...) list of variables, also normal mixed-case names are allowed</p>

<pre><code>enum InternalState {
        StateParam1,
        StateParam2,
        ...
        StateParam101
};
</code></pre>

<h3>2.11 Name files <code>like_this.cpp</code></h3>

<p>This is the most readable format, so we choose that when we don't have a reason to do something else.</p>

<p>The .h files should be put in the same directory as the .cpp files, not in some special "include" directory, for easier navigation between the files.</p>

<p>When a class spans across multiple files, these files must be named with the name of the class, followed by an underscore and a subsection name.</p>

<pre><code>class RenderWorld;
</code></pre>

<p>files:</p>

<pre><code>render_world.h
render_world_load.cpp
render_world_demo.cpp
render_world_portals.cpp
</code></pre>

<h3>2.12 Order class sections as follows</h3>

<ol>
<li>list of friend classes</li>
<li>public variables</li>
<li>public methods</li>
<li>protected variables</li>
<li>protected methods</li>
<li>private variables</li>
<li>private methods</li>
</ol>

<p>This allows the public interface to be easily found at the beginning of the class.</p>

<h3>2.13 Standard functions</h3>

<p>Getter and setter functions should look like this.</p>

<pre><code>Circle &amp;circle() {return _circle;}
void setCircle(Circle &amp;circle) {_circle = circle;}
</code></pre>

<p>The getter is called <code>circle</code> rather than <code>getCircle</code>, since the <code>get</code> prefix is superfluous. However, we use a <code>set</code> prefix to emphasize that we are changing the state of the object.</p>

<h3>2.14 Use sensible names</h3>

<p>Spell your names correctly.
Do not write the words "to" and "for" as "2" and "4".
All names and comments should be in American English.</p>

<h2>3. Braces</h2>

<h3>3.1 The bracing styles and when to use them</h3>

<p>There are three possible bracing styles:</p>

<pre><code>// Single line
int f() {return 3;}

// Opened on same line
while (true) {
    do(stuff);
    more(stuff);
}

// New line
int X::f()
{
    return 3;
}
</code></pre>

<p>The first style is typically used for getter and setter functions in the header file to make the header more compact.</p>

<p>The second style should never be used.</p>

<p>This third is the preferred for class declarations, function declarations and loops in the cpp file.</p>

<h3>3.2 Use braces to increase readability in nested scopes</h3>

<p>Instead of</p>

<pre><code>// BAD
while (a)
    if (b)
        c;
</code></pre>

<p>Write</p>

<pre><code>while (a) 
{
   if (b)
       c;
}
</code></pre>

<p>Only the innermost scope is allowed to omit its braces.</p>

<h3>3.3 Try to fit matching braces on a single screen</h3>

<p>The opening and closing of a brace should preferably fit on the same screen of code to increase readability.</p>

<p>Class and namespace definitions can of course cover more than one screen.</p>

<p>Function definitions can sometimes cover more than one screen -- if they are clearly structured.</p>

<h3>3.4 Use <code>continue</code>, <code>break</code> or even <code>goto</code> (!) to avoid deep nesting</h3>

<p>Code that is indented four or five times can be very hard to read. Often such indentation comes from a combination of loops and if-statements:</p>

<pre><code>// BAD
for (i=0; i&lt;parent-&gt;numChildren(); ++i) 
{
    Child child = parent-&gt;child(i);
    if (child-&gt;isCatOwner()) 
    {
        for (j=0; j&lt;child-&gt;numCats(); ++j) 
        {
            Cat cat = child-&gt;cat(j);
            if (cat-&gt;isGrey()) 
            {
                ...
</code></pre>

<p>Using continue to rewrite gives a clearer structure:</p>

<pre><code>for (i=0; i&lt;parent-&gt;numChildren(); ++i) 
{
    Child child = parent-&gt;child(i);
    if (!child-&gt;isCatOwner())
        continue;

    for (j=0; j&lt;child-&gt;numCats(); ++j) 
    {
        Cat cat = child-&gt;cat(j);
        if (!cat-&gt;isGrey())
            continue;

        ...
</code></pre>

<p>Excessive indentation can also come from error checking:</p>

<pre><code>// BAD
File f = openFile();
if (f.valid()) 
{
    std::string name;
    if (f.read(&amp;name)) 
    {
        int age;
        if (f.read(&amp;age)) 
        {
            ...
        }
    }
}
</code></pre>

<p>This is one of the few cases where goto can be validly used:</p>

<pre><code>File f = openFile();
if (!f.valid())
    goto err;

std::string name;
if (!f.read(&amp;name))
    goto err;

int age;
if (!f.read(&amp;age))
    goto err;

err:
    ...
</code></pre>

<h2>4. Indentation and Spacing</h2>

<h3>4.1 Use four spaces of indentation</h3>

<p>This is the default in Visual Studio and a good compromise between readability and succinctness.</p>

<h3>4.2 Think about evaluation order when placing spaces</h3>

<p>For statements, put a space between keywords and parenthesis, put a space before braces on the same line. Do not put any space before a semicolon.</p>

<pre><code>while (x == true)
{
    doStuff();
}
</code></pre>

<p>Placement of spaces in expressions is not that important.... but make sure that the placement of spaces reflects the evaluation order of the expression. I.e. begin by removing spaces around operators that have a higher order of precedence. This is OK:</p>

<pre><code>z = x*y(7)*(3 + p[3]) - 8;
</code></pre>

<p>Because * has higher precedence than - and =. This is confusing and not OK:</p>

<pre><code>// BAD
z=x * y(7) * (3+p [3])-8;
</code></pre>

<h3>4.3 Indent <code>#if</code> statements</h3>

<p>By default, the visual studio editor left flushes all preprocessing macros. This is idiotic and makes the code really hard to read, especially when the macros are nested:</p>

<pre><code>// BAD
void f()
{
#ifdef _WIN32
#define RUNNINGS_WINDOWS
#ifdef PRODUCTION
    bool print_error_messages = true
#else
    bool print_error_messages = false
#endif
#else
    bool win32 = false
#endif
</code></pre>

<p>Instead, indent your macros just as you would normal C code:</p>

<pre><code>void f()
{
    #ifdef _WIN32
        #define RUNNINGS_WINDOWS
        #ifdef PRODUCTION
            bool print_error_messages = true
        #else
            bool print_error_messages = false
        #endif
    #else
        bool win32 = false
    #endif
</code></pre>

<h3>4.4 Do not indent the entire file</h3>

<p>When the entire file is inside one (or several) namespaces, you should not indent the entire file. Indenting an entire file does not increase readability, it just means you will fit less code on the screen.</p>

<p>Instead, put a comment on the closing brace.</p>

<pre><code>namespace skinny
{

void x();
...

} // namespace skinny
</code></pre>

<p>When the namespace declaration does not cover the entire file, but only a screenfull or so, then it can be a good idea to indent it.</p>

<h3>4.5 Make lines reasonably long</h3>

<p>A lot of style guides say that lines should never be more than 80 characters long. This is overly restrictive. We all have displays that can show more than 80 characters per line.</p>

<p>Never write code like this:</p>

<pre><code>// BAD
int x = the + code +
    is + indented +
    and + I + dont +
    want + to + create
    + long + lines;
</code></pre>

<p>Either use less indentation or write longer lines.</p>

<p>Don't go crazy with line lengths, scrolling to see the end of the line is annnoying. </p>

<p>Also, make sure not to put very important stuff far to the right where it might be clipped from view.</p>

<h2>5. Comments</h2>

<h3>5.1 Use <code>//</code> for descriptive comments <code>/*</code> for disabling code</h3>

<p><code>//</code> comments are better for comments that you want to leave in the code, because they don't have any nesting problems, it is easy to see what is commented, etc.</p>

<p><code>/*</code> is useful when you want to quickly disable a piece of code.</p>

<h3>5.2 Do not leave disabled code in the source</h3>

<p>Commenting out old bad code with <code>/*</code> ... <code>*/</code> is useful and necessary.</p>

<p>It can be useful to leave the old commented out code in the source file for a while, while you check that the new code does not have any bugs, performance problems, etc. But once you are sure of that you should remove the commented out code from the file.</p>

<p>Having a lot of old, unused, commented out code in the source files makes them harder to read, because you constantly ask yourself why was this commented out, maybe the solution to my problem lies in this commented out code, etc. Source control already keeps a version history, we don't need to keep old code in comments.</p>

<h3>5.3 Put interface documentation in the .h file</h3>

<p>Put interface (function and class documentation) in the .h file. This makes it easier to find all the relevant interface documentation for someone browsing the .h files.</p>

<p>A drawback of this is that the .h files will become bigger and harder to grasp, but that is a price we are willing to pay.</p>

<h3>5.4 Use Doxygen syntax for interface documentation</h3>

<p>Doxygen is a well established standard for interface documentation.</p>

<p>We use the Javadoc-syntax for documentation (///) rather than the QT syntax (//!), because it is easier to type. Use @name to name groups of methods/members.</p>

<pre><code>/// @name Time functions

/// Elapsed seconds since the start of the program
float time();
</code></pre>

<p>Most public methods of classes in external interfaces should be documented. Private methods and private variables can be documented when that increases the understanding of the class.</p>

<h3>5.5 Use comments as hints to the reader</h3>

<p>The main source of information about what the code does should be the code itself. The code is always up-to-date, it doesn't lie and no extra effort is required to maintain it. You should not need to add comments that explain what the code does:</p>

<pre><code>// BAD

/// Returns the speed of the vehicle
float sp() {return _sp;}

// Computes speed from distance and time
s = d / t;

// Check for end of file
if (c == -1)
</code></pre>

<p>Instead, write code that is self-explanatory.</p>

<pre><code>float speed() {return _speed;}

speed = distance / time;

if (c == END_OF_FILE_MARKER)
</code></pre>

<p>Source code comments should be used as hints to the reader who tries to understand the code. They should point out when the code does something which is a little bit clever or tricky, something that may not be immediately obvious from reading just the code. In complicated algorithms that consist of several steps, they are also useful for identifying the separate steps and giving the user a sense of context.</p>

<pre><code>// Use Duff's device for loop unrolling
// See for example: http://en.wikipedia.org/wiki/Duff's_device
switch (count % 8)
{
  case 0:        do {  *to = *from++;
  case 7:              *to = *from++;
  case 6:              *to = *from++;
  case 5:              *to = *from++;
  case 4:              *to = *from++;
  case 3:              *to = *from++;
  case 2:              *to = *from++;
  case 1:              *to = *from++;
                    } while ((count -= 8) &gt; 0);
}
</code></pre>

<h3>5.6 Avoid boilerplate comments</h3>

<p>The purpose of comments is to convey information. Avoid big cut-and-paste boilerplate comments in front of classes and functions. Make the comments succint and to the point. There is no point in repeating information in the comment that is already in the function header, like this:</p>

<pre><code>// BAD

/// @param p1  a point
/// @param p2  another point
/// @return The distance between p1 and p2
float distance(const Vector3 &amp;p1, const Vector3 &amp;p2);
</code></pre>

<h3>5.7 Don't put high level documentation in source code comments</h3>

<p>Source code comments are not and should not be the only kind of documentation. Source code comments are good for documenting details that are directly related to the code, such as reference documentation for an API.</p>

<p>Aside from detail documentation, systems also need high level documentation. The high level documentation should provide an overview of the system and an entry point for programmers who are new to the system. It should explain the different concepts that are used in the system and how they relate to each other, the goals of system and the different design choices that have been made.</p>

<p>High level documentation should not be put in source code comments. That makes it fragmented and hard to read. Instead, it should be created as an HTML document, where the user can read it as a single continuous text with nice fonts, illustrations, examples, etc.</p>

<h3>5.8 Comment a file like this</h3>

<pre><code>/// @file
///
/// This file contains classes for parsing and generating
/// XML files.
///
/// @author John Doe
</code></pre>

<p>There is no need for putting dates, etc in the file comment. You can read that from the SCM repository. <br>
I consider the author name a notable excepion, since it can be useful for tracking sources outside the version control.</p>

<p>If the file contains only a single class, you typically do not need a file comment, just a comment for the main class.</p>

<h3>5.9 Comment a class like this</h3>

<pre><code>/// Contains the result of a raycast.
///
/// @ingroup Physics
class RaycastResult
</code></pre>

<p>Every class should have a @ingroup definition since that makes them easier to browse in Doxygen.</p>

<p>If a file contains a lot of classes or other logically separate parts, you can add a divider line between them to increase readability:</p>

<pre><code>// ----------------------------------------------------------------------
</code></pre>

<h3>5.10 Comment a function like this</h3>

<pre><code>/// Cost in going from @a p1 to @a p2.
/// @note Cost of going in z is 2 times as expensive.
static inline float cost(const Vector3 &amp;p1, const Vector3 &amp;p2)
</code></pre>

<p>Do not add a super heavy boilerplate comments to functions with parameters, return values, etc. Such comments tend to contain mostly fluff anyway. They convey no more information than a simple comment and they make it much harder to get an overview of the code.</p>

<p>I.e. avoid fluff pieces like this:</p>

<pre><code>// BAD

/************************************************************
 * Name: cost
 *
 * Description: Returns the cost of going from point p1 to p2.
 * Note: Cost of going in z direction is 2 times as expensive.
 *
 * Parameters:
 *     p1 - The one point
 *     p2 - The other point
 * Return value:
 *     The cost of going from p1 to p2.
 *************************************************************/
 static inline float cost(const Vector3 &amp;p1, const Vector3 &amp;p2)
</code></pre>

<h2>6. Language usage</h2>

<h3>6.1 Use precision specification</h3>

<p>For floating point values use precision specifications unless there is an explicit need for a double.</p>

<pre><code>float f = 0.5f;
</code></pre>

<p>Instead of</p>

<pre><code>float f = 0.5;  // 0.5 here is a double constant
</code></pre>

<p>And</p>

<pre><code>float f = 1.0f;
</code></pre>

<p>Instead of</p>

<pre><code>float f = 1.f;
</code></pre>

<h3>6.2 Use <code>const</code> as much as possible.</h3>

<p>Use:</p>

<pre><code>const int *p;           // pointer to const int
int * const p;          // const pointer to int
const int * const p;    // const pointer to const int
</code></pre>

<p>Don’t use:</p>

<pre><code>int const *p;
</code></pre>

<h3>6.3 Always make class methods <code>const</code> when they do not modify any class variables.</h3>

<p>Avoid use of <code>const_cast</code>.  When object is needed to be modified, but only const versions are accessible, create a function that clearly gives an editable version of the object.  This keeps the control of the ‘const-ness’ in the hands of the object and not the user.</p>

<p>Return <code>const</code> objects unless the general usage of the object is to change its state.  For example, media objects should be const to a majority of the code, while base Entity objects tend to have their state modified by a variety of systems, and so are ok to leave non-const.</p>

<h3>6.4 Function overloading should be avoided in most cases.</h3>

<p>Instead of:</p>

<pre><code>const animation* getAnim( int index ) const;
const animation* getAnim( const char *name ) const;
const animation* getAnim( float randomDiversity ) const;
</code></pre>

<p>Use:</p>

<pre><code>const animation* getAnimByIndex( int index ) const;
const animation* getAnimByName( const char *name ) const;
const animation* getRandomAnim( float randomDiversity ) const;
</code></pre>

<p>Explicitly named functions tend to be less prone to programmer error and inadvertent calls to functions due to wrong data types being passed in as arguments. For example:</p>

<pre><code>randomAnimation = getAnim( 0 );
</code></pre>

<p>This could be meant as a call to get a random animation, but the compiler would interpret it as a call to get one by index.</p>

<p>Overloading functions for the sake of adding <code>const</code> accessible function is allowable:</p>

<pre><code>class AnimatedEntity
{
    Animator*        getAnimator( void );
    const Animator*  getAnimator( void ) const;
};
</code></pre>

<p>In this case, a const version of <code>getAnimator</code> was provided in order to allow <code>getAnimator</code> to be called from <code>const</code> functions.</p>

<h2>7. Design and Implementation Issues</h2>

<h3>7.1 Optimize wisely</h3>

<p>All the code in the engine does not have to be super optimized. Code that only runs once-per-frame has very little impact on performance. Do not spend effort on optimizing that code. Consider what are the heavy-duty number-crunching parts of the code and focus your efforts on them. Use the profiler as a guide to finding the parts of the code that matter.</p>

<p><em>Be very wary of sacrificing simplicity for code efficiency.</em> Your code will most likely live for a long time and go through several rounds of optimization and debugging. Every time you add complexity you make future optimizations more difficult. Thus, an optimization that makes the code faster today may actually make it slower in the long run by preventing future optimizations. Always strive for the simplest possible code. Only add complexity when it is absolutely necessary.</p>

<p>Be aware that the rules of optimization have changed. Cycle counts matter less. Memory access patterns and parallelization matter more. Write your optimizations so that they touch as little memory as possible and as linearly as possible. Write the code so that it can be parallelized and moved to SPUs. Focus on data layouts and data transforms. Read up on data oriented design.</p>

<h2>8. Miscellaneous</h2>

<h3>8.1 Use <code>#pragma once</code> to avoid multiple header inclusion</h3>

<p>All current compilers understand the #pragma once directive. And it is a lot easier to read than the standard #ifndef syntax:</p>

<pre><code>// BAD
#ifndef _MY_UNIQUE_HEADER_NAME_H_
#define _MY_UNIQUE_HEADER_NAME_H_
   ...
#endif

// GOOD
#pragma once
</code></pre>

<p>On MSVC is also much faster because it doesn't need to open the file multiple times.</p>