-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
2314 lines (1761 loc) · 87 KB
/
index.html
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
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<!-- saved from url=(0049)https://google.github.io/styleguide/cppguide.html -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HypED C++ Style Guide</title>
<link rel="stylesheet" type="text/css" href="./include/styleguide.css">
<script language="javascript" src="./include/styleguide.js"></script>
<!--link rel="shortcut icon" type="image/x-icon" href="https://www.google.com/favicon.ico"-->
</head>
<!-------------------------------------------------------------------------------------------------------------------
General Introduction
-------------------------------------------------------------------------------------------------------------------->
<body onload="initStyleGuide();">
<div id="content">
<h1>HypED C++ Style Guide</h1>
<div class="horizontal_toc" id="tocDiv"></div>
<div class="main_body">
<h2 class="ignoreLink" id="Background">Background</h2>
<p>C++ is the main development language in HypED. Since we will have dozens of developers coding
for the pod, it is very important that everyone adheres to the same code style. That way,
our code will be easily readable and navigable by anyone, not just the author.
</p>
<p>Note that this guide is not a C++ tutorial: we assume that the reader is familiar with the
language. If you do not understand something then it either means that there is a typo, in which
case please tell Brano, or that you need to brush up on your C++.
</p>
<h3 id="Goals" style="left: -46px; position: relative;">Goals of the Style Guide</h3>
<div class="stylebody">
<p>Why do we have this document?</p>
<p>There are a few core goals that we believe this guide should serve. These are the fundamental
<b>why</b>s that underlie all of the individual rules. By bringing these ideas to the fore, we
hope to ground discussions and make it clearer why the rules are in
place and why particular decisions have been made. If you understand what goals each rule is
serving, it should be clearer to everyone when a rule may be waived (some can be), and what
sort of argument or alternative would be necessary to change a rule in the guide.</p>
<p>The goals of the style guide as we currently see them are as follows:</p>
<dl>
<dt>Style rules should pull their weight</dt>
<dd>The benefit of a rule is measured relative to the codebase we would get without the rule,
so a rule against a very harmful practice may still have a small benefit if people are unlikely
to do it anyway. This principle mostly explains the rules we don’t have, rather than the
rules we do: for example, <code>goto</code> contravenes many of the following principles,
but is already vanishingly rare, so the Style Guide doesn’t discuss it.</dd>
<dt>Optimize for the reader, not the writer</dt>
<dd>Due to time constraints, much of our code might end up being developed solely by individual
people. Hence it is very important that everyone can read and navigate everyone elses code
easily should they need to take over the work.
We optimize for the ease of reading, maintaining, and debugging code in our codebase rather
than ease of writing said code. "Leave a trace for the reader" is a particularly common
sub-point of this principle.
</dd>
</dl>
<p>The intent of this document is to provide maximal guidance with reasonable restriction. As always,
common sense and good taste should prevail. By this we specifically refer to the established
conventions of the entire C++ community, not just your personal preferences or those
of your team. Be skeptical about and reluctant to use clever or unusual constructs: the absence
of a prohibition is not the same as a license to proceed. Use your judgment, and if you are
unsure, please don't hesitate to ask on Slack to get additional input.
</p>
</div>
<!-------------------------------------------------------------------------------------------------------------------
Header Files
-------------------------------------------------------------------------------------------------------------------->
<h2 id="Header_Files" style="left: -46px; position: relative;">Header Files</h2>
<p>In general, every
<code>.cpp</code> file should have an associated
<code>.hpp</code> file. There are some common exceptions, such as unittests and small
<code>.cpp</code> files containing just a
<code>main()</code> function.</p>
<p>Correct use of header files can make a huge difference to the readability, size and performance
of your code.</p>
<a id="The_-inl.h_Files"></a>
<h3 id="Self_contained_Headers" style="left: -46px; position: relative;">Self-contained Headers</h3>
<div class="summary">
<p>Header files should be self-contained (compile on their own) and end in
<code>.hpp</code>. Non-header (<code>.cpp</code>) files must not be included
from other files.
</div>
<div class="stylebody">
<p>Users should not have to adhere to special conditions to include the header. Specifically,
a header should have <a href="#The__define_Guard">header guards</a> and include all other
headers it needs.</p>
<p>Place the definitions for template and inline functions in the same file as their declarations.
The definitions of these constructs must be included into every
<code>.cpp</code> file that uses them, or the program may fail to link in some build configurations.
Do not move these definitions to separately included header files (e.g.
<code>-inl.hpp</code>).</p>
</div>
<h3 id="The__define_Guard" style="left: -46px; position: relative;">The #define Guard</h3>
<div class="summary">
<p>All header files should have
<code>#define</code> guards to prevent multiple inclusion. The format of the symbol name should be
<code><i><PROJECT></i>_<i><PATH></i>_<i><FILE></i>_HPP_</code>.</p>
</div>
<div class="stylebody">
<p>To guarantee uniqueness, they should be based on the full path in a project's source tree. For
example, the file
<code>foo/src/bar/baz.hpp</code> in project
<code>foo</code> should have the following guard:
</p>
<pre>#ifndef FOO_BAR_BAZ_HPP_
#define FOO_BAR_BAZ_HPP_
...
#endif // FOO_BAR_BAZ_HPP_
</pre>
</div>
<h3 id="Names_and_Order_of_Includes" style="left: -46px; position: relative;">Names and Order of Includes</h3>
<div class="summary">
<p>Use standard order for readability and to avoid hidden dependencies: Related header, C library,
C++ library, other libraries' headers, your project's headers.</p>
</div>
<div class="stylebody">
<p>
All of a project's header files should be listed as descendants of the project's source directory without
use of UNIX directory shortcuts
<code>.</code> (the current directory) or
<code>..</code> (the parent directory). For example,
<code>project/src/base/logging.hpp</code> should be included as:</p>
<pre>#include "base/logging.hpp"
</pre>
<p>In
<code><var>dir/foo</var>.cpp</code> or
<code><var>dir/foo_test</var>.cpp</code>, whose main purpose is to implement or test the stuff in
<code><var>dir2/foo2</var>.hpp</code>, order your includes as follows:</p>
<ol>
<li>
<code><var>dir2/foo2</var>.hpp</code>.</li>
<li>C system files.</li>
<li>C++ system files.</li>
<li>Other libraries'
<code>.h</code>/<code>.hpp</code> files.
</li>
<li>
Your project's
<code>.hpp</code> files.
</li>
</ol>
<p>With the preferred ordering, if
<code><var>dir2/foo2</var>.hpp</code> omits any necessary includes, the build of
<code><var>dir/foo</var>.cpp</code> or
<code><var>dir/foo</var>_test.cpp</code> will break. Thus, this rule ensures that build breaks show up first for the people working
on these files, not for innocent people in other packages.</p>
<p>
<code><var>dir/foo</var>.cpp</code> and
<code><var>dir2/foo2</var>.hpp</code> are usually in the same directory (e.g.
<code>base/basictypes_test.cpp</code> and
<code>base/basictypes.hpp</code>), but may sometimes be in different directories too.</p>
<p>Within each section the includes should be ordered alphabetically.</p>
<p>You should include all the headers that define the symbols you rely upon. If you rely on symbols from
<code>bar.hpp</code>, don't count on the fact that you included
<code>foo.hpp</code> which (currently) includes
<code>bar.hpp</code>: include
<code>bar.hpp</code> yourself, unless
<code>foo.hpp</code> explicitly demonstrates its intent to provide you the symbols of
<code>bar.hpp</code>. However, any includes present in the related header do not need to be included again in the
related
<code>.cpp</code> (i.e.,
<code>foo.cpp</code> can rely on
<code>foo.hpp</code>'s includes).</p>
<p>For example, the includes in
<code>project/src/foo/internal/fooserver.cpp</code> might look like this:</p>
<pre>#include "foo/server/fooserver.hpp"
#include <sys/types.h>
#include <unistd.h>
#include <hash_map>
#include <vector>
#include "base/basictypes.hpp"
#include "base/commandlineflags.hpp"
#include "foo/server/bar.hpp"
</pre>
</div>
<!-------------------------------------------------------------------------------------------------------------------
Naming
-------------------------------------------------------------------------------------------------------------------->
<h2 id="Naming" style="left: -46px; position: relative;">Naming</h2>
<p>The style of a name immediately informs us what sort of thing the named entity is: a type,
a variable, a function, a constant, a macro, etc., without requiring us to search for the declaration
of that entity. The pattern-matching engine in our brains relies a great deal on these naming rules.
</p>
<p>Naming rules are pretty arbitrary, but we feel that consistency is more important than individual
preferences in this area, so regardless of whether you find them sensible or not, the rules are
the rules.</p>
<h3 id="General_Naming_Rules" style="left: -46px; position: relative;">General Naming Rules</h3>
<div class="summary">
<p>Names should be descriptive; avoid abbreviation.</p>
</div>
<div class="stylebody">
<p>Give as descriptive a name as possible, within reason. Do not worry about saving horizontal space
as it is far more important to make your code immediately understandable by a new reader. Do
not use abbreviations that will be ambiguous or unfamiliar to people who may reasonably be expected
to read the code, and do not abbreviate by deleting letters within a word.</p>
<pre>int price_count_reader; // No abbreviation.
int num_errors; // "num" is a widespread convention.
int num_dns_connections; // Most people know what "DNS" stands for.
</pre>
<pre class="badcode">int n; // Meaningless.
int nerr; // Ambiguous abbreviation.
int n_comp_conns; // Ambiguous abbreviation.
int wgc_connections; // Only your group knows what this stands for.
int pc_reader; // Lots of things can be abbreviated "pc".
int cstmr_id; // Deletes internal letters.
</pre>
<p>Note that certain universally-known abbreviations are OK, such as
<code>i</code> for an iteration variable and
<code>T</code> for a template parameter.</p>
<p>Template parameters should follow the naming style for their category: type template parameters
should follow the rules for
<a href="#Type_Names">type names</a>, and non-type template parameters should follow the rules for
<a href="#Variable_Names">
variable names</a>.
</p>
</div>
<h3 id="File_Names" style="left: -46px; position: relative;">File Names</h3>
<div class="summary">
<p>Filenames should be all lowercase and can include underscores (<code>_</code>) or dashes
(<code>-</code>) for separating words. Underscores are preferred.</p>
</div>
<div class="stylebody">
<p>C++ files should end in
<code>.cpp</code> and header files should end in
<code>.hpp</code>.
<p>In general, make your filenames very specific. For example, use
<code>http_server_logs.hpp</code> rather than
<code>logs.hpp</code>. A very common case is to have a pair of files called, e.g.,
<code>foo_bar.hpp</code> and
<code>foo_bar.cpp</code>, defining a class called
<code>FooBar</code>.</p>
<p>This rule may not apply in testing. For more information see <a href="#Test_File_Names">Test File Names</a>.</p>
</div>
<h3 id="Type_Names" style="left: -46px; position: relative;">Type Names</h3>
<div class="summary">
<p>Type names start with a capital letter and have a capital letter for each new word, with no underscores:
<code>MyExcitingClass</code>,
<code>MyExcitingEnum</code>.</p>
</div>
<div class="stylebody">
<p>The names of all types — classes, structs, type aliases, enums, and type template parameters
— have the same naming convention. Type names should start with a capital letter and have a
capital letter for each new word. No underscores. For example:</p>
<pre>// classes and structs
class UrlTable { ...
class UrlTableTester { ...
struct UrlTableProperties { ...
// typedefs
typedef hash_map<UrlTableProperties *, string> PropertiesMap;
// using aliases
using PropertiesMap = hash_map<UrlTableProperties *, string>;
// enums
enum UrlTableErrors { ...
</pre>
</div>
<h3 id="Variable_Names" style="left: -46px; position: relative;">Variable Names</h3>
<div class="summary">
<p>The names of variables (including function parameters) and data members are all lowercase, with
underscores between words. Data members of classes (but not structs) additionally have trailing
underscores. For instance:
<code>a_local_variable</code>,
<code>a_struct_data_member</code>,
<code>a_class_data_member_</code>.</p>
</div>
<div class="stylebody">
<h4 class="stylepoint_subsection">Common Variable names</h4>
<p>For example:</p>
<pre>string table_name; // OK - uses underscore.
string tablename; // OK - all lowercase.
</pre>
<pre class="badcode">string tableName; // Bad - mixed case.
</pre>
<h4 class="stylepoint_subsection">Class Data Members</h4>
<p>Data members of classes, both static and non-static, are named like ordinary nonmember variables,
but with a trailing underscore.</p>
<pre>class TableInfo {
...
private:
string table_name_; // OK - underscore at end.
string tablename_; // OK.
static Pool<TableInfo>* pool_; // OK.
};
</pre>
<h4 class="stylepoint_subsection">Struct Data Members</h4>
<p>Data members of structs, both static and non-static, are named like ordinary nonmember variables.
They do not have the trailing underscores that data members in classes have.</p>
<pre>struct UrlTableProperties {
string name;
int num_entries;
static Pool<UrlTableProperties>* pool;
};
</pre>
<!--TODO <p>See <a href="#Structs_vs._Classes">Structs vs. Classes </a> for a discussion of when to use
a struct versus a class.</p>-->
</div>
<h3 id="Constant_Names" style="left: -46px; position: relative;">Constant Names</h3>
<div class="summary">
<p>Variables declared constexpr or const, and whose value is fixed for the duration of the program,
are named with a leading "k" followed by mixed case. For example:</p>
</div>
<pre>const int kDaysInAWeek = 7;
</pre>
<div class="stylebody">
<p>All such variables with static storage duration (i.e. statics and globals, see
<a href="http://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration">
Storage Duration</a> for details) should be named this way. This convention is optional for
variables of other storage classes, e.g. automatic variables, otherwise the usual variable
naming rules apply.</p>
<p>
</p>
</div>
<h3 id="Function_Names" style="left: -46px; position: relative;">Function Names</h3>
<div class="summary">
<p>Regular functions have mixed case; accessors and mutators may be named like variables.</p>
</div>
<div class="stylebody">
<p>Ordinarily, functions should start with a lowercase letter and have a capital letter for each new
word. Such names should not have underscores. Prefer to capitalize acronyms
as single words (i.e.
<code>readImu()</code>, not
<code>readIMU()</code>).</p>
<pre>addTableEntry()
deleteUrl()
openFileOrDie()
</pre>
</div>
<h3 id="Namespace_Names" style="left: -46px; position: relative;">Namespace Names</h3>
<div class="summary">
Namespace names are all lower-case. Top-level namespace names are based on the project name . Avoid collisions
between nested namespaces and well-known top-level namespaces.
</div>
<h3 id="Enumerator_Names" style="left: -46px; position: relative;">Enumerator Names</h3>
<div class="summary">
<p>Enumerators (for both scoped and unscoped enums) should be named like
<a href="#Constant_Names">constants</a> (e.g. <code>kEnumName</code>).</p>
</div>
<div class="stylebody">
<p>The individual enumerators should be named like
<a href="#Constant_Names">constants</a>.
The enumeration name, <code>UrlTableErrors</code>, is a type, and therefore mixed case.</p>
<pre>enum UrlTableErrors {
kOK = 0,
kErrorOutOfMemory,
kErrorMalformedInput,
};
</pre>
</div>
<h3 id="Macro_Names" style="left: -46px; position: relative;">Macro Names</h3>
<div class="summary">
<p>You're not really going to
<a href="#Preprocessor_Macros">
define a macro</a>, are you? If you do, they're like this:
<code>MY_MACRO_THAT_SCARES_SMALL_CHILDREN</code>.</p>
</div>
<div class="stylebody">
<p><!--TODO Please see the
<a href="#Preprocessor_Macros">description of macros</a>;--> In general macros should
<em>not</em> be used. However, if they are needed, then they should be named with all
capitals and underscores.</p>
<pre>#define ROUND(x) ...
#define PI_ROUNDED 3.0
</pre>
</div>
<h3 id="Exceptions_to_Naming_Rules" style="left: -46px; position: relative;">Exceptions to Naming Rules</h3>
<div class="summary">
<p>If you are naming something that is analogous to an existing C or C++ entity then you can follow
the existing naming convention scheme.</p>
</div>
<div class="stylebody">
<dl>
<dt>
<code>bigopen()</code>
</dt>
<dd>function name, follows form of
<code>open()</code>
</dd>
<dt>
<code>uint</code>
</dt>
<dd>
<code>typedef</code>
</dd>
<dt>
<code>bigpos</code>
</dt>
<dd>
<code>struct</code> or
<code>class</code>, follows form of
<code>pos</code>
</dd>
<dt>
<code>sparse_hash_map</code>
</dt>
<dd>STL-like entity; follows STL naming conventions</dd>
<dt>
<code>LONGLONG_MAX</code>
</dt>
<dd>a constant, as in
<code>INT_MAX</code>
</dd>
</dl>
</div>
<!-------------------------------------------------------------------------------------------------------------------
Comments
-------------------------------------------------------------------------------------------------------------------->
<h2 id="Comments" style="left: -46px; position: relative;">Comments</h2>
<p>Code should be documented well. This serves several purposes. Well documented code is easier for others to understand,
which leads to better code maintainability. Furthermore, once a programmer needs to document code, they need to think
about the code structure, design, and functionality. This thinking fosters writing better code in general. Documentation
can also be used to generate html site for easy navigation through project’s APIs.</p>
<p>Though a pain to write, comments are absolutely vital to keeping our code readable. The following
rules describe what you should comment and where. But remember: while comments are very important,
the best code is self-documenting. Giving sensible names to types and variables is much better
than using obscure names that you must then explain through comments.</p>
<p>When writing your comments, write for your audience: the next contributor who will need to understand
your code. Be generous — the next one may be you!</p>
<h3 id="Comment_Style" style="left: -46px; position: relative;">Comment Style</h3>
<div class="summary">
<p>Use either the
<code>//</code> or
<code>/* */</code> syntax, as long as you are consistent.</p>
</div>
<div class="stylebody">
<p>You can use either the
<code>//</code> or the
<code>/*
*/</code> syntax; however,
<code>//</code> is
<em>much</em> more common. Be consistent with how you comment and what style you use where.</p>
</div>
<h3 id="File_Comments" style="left: -46px; position: relative;">File Comments</h3>
<div class="summary">
<p>File comments describe the contents of a file. If a file declares, implements, or tests exactly
one abstraction that is documented by a comment at the point of declaration, file comments
are not required. All other files must have file comments.</p>
</div>
<div class="stylebody">
<h4 class="stylepoint_subsection">Legal Notice and Author Line
</h4>
<p>Every file should start with the following license boilerplate.</p>
<pre>/*
* Author:
* Organisation: HYPED
* Date:
* Description: <What is this file for?>
*
* Copyright 2018 HYPED
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<p>If more people contribute to the same file, include all of them on the 'Authors:' line.
Consider deleting the line if there is too many authors.
</p>
<h4 class="stylepoint_subsection">File Contents</h4>
<p>If a
<code>.hpp</code> declares multiple abstractions, the file-level comment should broadly describe the contents
of the file, and how the abstractions are related. A 1 or 2 sentence file-level comment may
be sufficient. The detailed documentation about individual abstractions belongs with those
abstractions, not at the file level.</p>
<p>Do not duplicate comments in both the
<code>.hpp</code> and the
<code>.cpp</code>. Duplicated comments diverge.</p>
</div>
<h3 id="Class_Comments" style="left: -46px; position: relative;">Class Comments</h3>
<div class="summary">
<p>Every non-obvious class declaration should have an accompanying comment that describes what it
is for and how it should be used.</p>
</div>
<div class="stylebody">
<pre>// Iterates over the contents of a GargantuanTable.
// Example:
// GargantuanTableIterator* iter = table->newIterator();
// for (iter->seek("foo"); !iter->done(); iter->next()) {
// process(iter->key(), iter->value());
// }
// delete iter;
class GargantuanTableIterator {
...
};
</pre>
<p>The class comment should provide the reader with enough information to know how and when to use
the class, as well as any additional considerations necessary to correctly use the class.</p>
<p>The class comment is often a good place for a small example code snippet demonstrating a simple
and focused usage of the class.</p>
<p>When sufficiently separated (e.g.
<code>.hpp</code> and
<code>.cpp</code> files), comments describing the use of the class should go together with its interface definition;
comments about the class operation and implementation should accompany the implementation of
the class's methods.</p>
</div>
<h3 id="Function_Comments" style="left: -46px; position: relative;">Function Comments</h3>
<div class="summary">
<p>Declaration comments describe use of the function (when it is non-obvious); comments at the definition
of a function describe operation.
</p>
</div>
<div class="stylebody">
<h4 class="stylepoint_subsection">Function Declarations</h4>
<p>Almost every function declaration should have comments immediately preceding it that describe
what the function does and how to use it. These comments may be omitted only if the function
is simple and obvious (e.g. simple accessors for obvious properties of the class). These comments
should be descriptive ("Opens the file") rather than imperative ("Open the file"); the comment
describes the function, it does not tell the function what to do. In general, these comments
do not describe how the function performs its task. Instead, that should be left to comments
in the function definition.</p>
<p>Each function declaration should be preceded by a block comment with a brief description of
how the function should be used, descriptions of all input parameters, and explanation of the
return value (if any). Implementation description of a method can be further extended at the
point of definition.</p>
<pre>/**
* @brief { function_description }
*
* @param[in] c { parameter_description }
* @param[in] i { parameter_description }
*
* @return { description_of_the_return_value }
*/
int foo (char c, int i);
</pre>
<p>However, do not be unnecessarily verbose or state the completely obvious. Notice below that it
is not necessary to say "returns false otherwise" because this is implied.
</p>
<pre>/**
* @brief Returns true if the table cannot hold any more entries.
*/
bool isTableFull();
</pre>
<p>When documenting function overrides, focus on the specifics of the override itself, rather than
repeating the comment from the overridden function. In many of these cases, the override needs
no additional documentation and thus no comment is required.</p>
<p>When commenting constructors and destructors, remember that the person reading your code knows
what constructors and destructors are for, so comments that just say something like "destroys
this object" are not useful. Document what constructors do with their arguments (for example,
if they take ownership of pointers), and what cleanup the destructor does. If this is trivial,
just skip the comment. It is quite common for destructors not to have a header comment.</p>
<h4 class="stylepoint_subsection">Function Definitions</h4>
<p>If there is anything tricky about how a function does its job, the function definition should
have an explanatory comment. For example, in the definition comment you might describe any
coding tricks you use, give an overview of the steps you go through, or explain why you chose
to implement the function in the way you did rather than using a viable alternative. For instance,
you might mention why it must acquire a lock for the first half of the function but why it
is not needed for the second half.</p>
<p>Note you should
<em>not</em> just repeat the comments given with the function declaration, in the
<code>.hpp</code> file or wherever. It's okay to recapitulate briefly what the function does, but the focus
of the comments should be on how it does it.</p>
</div>
<h3 id="Variable_Comments" style="left: -46px; position: relative;">Variable Comments</h3>
<div class="summary">
<p>In general the actual name of the variable should be descriptive enough to give a good idea of
what the variable is used for. In certain cases, more comments are required.</p>
</div>
<div class="stylebody">
<h4 class="stylepoint_subsection">Class Data Members</h4>
<p>The purpose of each class data member (also called an instance variable or member variable) must
be clear. If there are any invariants (special values, relationships between members, lifetime
requirements) not clearly expressed by the type and name, they must be commented. However,
if the type and name suffice (
<code>int
num_events_;</code>), no comment is needed.</p>
<p>In particular, add comments to describe the existence and meaning of sentinel values, such as
nullptr or -1, when they are not obvious. For example:</p>
<pre>private:
// Used to bounds-check table accesses. -1 means
// that we don't yet know how many entries the table has.
int num_total_entries_;
</pre>
<h4 class="stylepoint_subsection">Global Variables</h4>
<p>All global variables should have a comment describing what they are, what they are used for,
and (if unclear) why it needs to be global. For example:</p>
<pre>// The total number of tests cases that we run through in this regression test.
const int kNumTestCases = 6;
</pre>
</div>
<h3 id="Implementation_Comments" style="left: -46px; position: relative;">Implementation Comments</h3>
<div class="summary">
<p>In your implementation you should have comments in tricky, non-obvious, interesting, or important
parts of your code.</p>
</div>
<div class="stylebody">
<h4 class="stylepoint_subsection">Explanatory Comments</h4>
<p>Tricky or complicated code blocks should have comments before them. Example:</p>
<pre>// Divide result by two, taking into account that x
// contains the carry from the add.
for (int i = 0; i < result->size(); i++) {
x = (x << 8) + (*result)[i];
(*result)[i] = x >> 1;
x &= 1;
}
</pre>
<h4 class="stylepoint_subsection">Line Comments</h4>
<p>Also, lines that are non-obvious should get a comment at the end of the line. These end-of-line
comments should be separated from the code by 2 spaces. Example:</p>
<pre>// If we have enough memory, mmap the data portion too.
mmap_budget = max<int64>(0, mmap_budget - index_->length());
if (mmap_budget >= data_size_ && !MmapData(mmap_chunk_bytes, mlock))
return; // Error already logged.
</pre>
<p>Note that there are both comments that describe what the code is doing, and comments that mention
that an error has already been logged when the function returns.
</p>
<p>If you have several comments on subsequent lines, it can often be more readable to line them
up:</p>
<pre>doSomething(); // Comment here so the comments line up.
doSomethingElseThatIsLonger(); // Two spaces between the code and the comment.
{ // One space before comment when opening a new scope is allowed,
// thus the comment lines up with the following comments and code.
doSomethingElse(); // Two spaces before line comments normally.
}
std::vector<string> list{
// Comments in braced lists describe the next element...
"First item",
// .. and should be aligned appropriately.
"Second item"};
</pre>
<h4 class="stylepoint_subsection">Function Argument Comments</h4>
<p>When the meaning of a function argument is nonobvious, consider one of the following remedies:</p>
<ul>
<li>If the argument is a literal constant, and the same constant is used in multiple function calls
in a way that tacitly assumes they're the same, you should use a named constant to make that
constraint explicit, and to guarantee that it holds.</li>
<li>Consider changing the function signature to replace a
<code>bool</code> argument with an
<code>enum</code> argument. This will make the argument values self-describing.</li>
<li>For functions that have several configuration options, consider defining a single class or
struct to hold all the options , and pass an instance of that. This approach has several
advantages. Options are referenced by name at the call site, which clarifies their meaning.
It also reduces function argument count, which makes function calls easier to read and write.
As an added benefit, you don't have to change call sites when you add another option.
</li>
<li>Replace large or complex nested expressions with named variables.</li>
<li>As a last resort, use comments to clarify argument meanings at the call site.</li>
</ul>
Consider the following example:
<pre class="badcode">// What are these arguments?
const DecimalNumber product = calculateProduct(values, 7, false, nullptr);
</pre>
<p>versus:</p>
<pre>ProductOptions options;
options.set_precision_decimals(7);
options.set_use_cache(ProductOptions::kDontUseCache);
const DecimalNumber product =
calculateProduct(values, options, /*completion_callback=*/nullptr);
</pre>
<h4 class="stylepoint_subsection">Don'ts</h4>
<p>Do not state the obvious. In particular, don't literally describe what code does, unless the
behavior is nonobvious to a reader who understands C++ well. Instead, provide higher level
comments that describe
<i>why</i>
the code does what it does, or make the code self describing.</p>
Compare this:
<pre class="badcode">// Find the element in the vector. <-- Bad: obvious!
auto iter = std::find(v.begin(), v.end(), element);
if (iter != v.end()) {
process(element);
}
</pre> To this:
<pre>// Process "element" unless it was already processed.
auto iter = std::find(v.begin(), v.end(), element);
if (iter != v.end()) {
process(element);
}
</pre> Self-describing code doesn't need a comment. The comment from the example above would be obvious:
<pre>if (!isAlreadyProcessed(element)) {
process(element);
}
</pre>
</div>
<h3 id="Punctuation,_Spelling_and_Grammar" style="left: -46px; position: relative;">Punctuation, Spelling and Grammar</h3>
<div class="summary">
<p>Pay attention to punctuation, spelling, and grammar; it is easier to read well-written comments
than badly written ones.
</p>
</div>
<div class="stylebody">
<p>Comments should be as readable as narrative text, with proper capitalization and punctuation.
In many cases, complete sentences are more readable than sentence fragments. Shorter comments,
such as comments at the end of a line of code, can sometimes be less formal, but you should
be consistent with your style.</p>
<p>Although it can be frustrating to have a code reviewer point out that you are using a comma when
you should be using a semicolon, it is very important that source code maintain a high level
of clarity and readability. Proper punctuation, spelling, and grammar help with that goal.
</p>
</div>
<h3 id="TODO_Comments" style="left: -46px; position: relative;">TODO Comments</h3>
<div class="summary">
<p>Use
<code>TODO</code> comments for code that is temporary, a short-term solution, or good-enough but not perfect.</p>
</div>
<div class="stylebody">
<p>
<code>TODO</code>s should include the string
<code>TODO</code> in all caps, followed by the name, e-mail address, bug ID, or other identifier of the person
or issue with the best context about the problem referenced by the
<code>TODO</code>. The main purpose is to have a consistent
<code>TODO</code> that can be searched to find out how to get more details upon request. A
<code>TODO</code> is not a commitment that the person referenced will fix the problem. Thus when you create
a
<code>TODO</code> with a name, it is almost always your name that is given.</p>
<div>
<pre>// TODO([email protected]): Use a "*" here for concatenation operator.
// TODO(Zeke) change this to use relations.
// TODO(bug 12345): remove the "Last visitors" feature
</pre>
</div>
<p>If your
<code>TODO</code> is of the form "At a future date do something" make sure that you either include a very specific
date ("Fix by November 2005") or a very specific event ("Remove this code when all clients
can handle XML responses.").</p>
</div>
<!-------------------------------------------------------------------------------------------------------------------
Formatting
-------------------------------------------------------------------------------------------------------------------->
<h2 id="Formatting" style="left: -46px; position: relative;">Formatting</h2>
<p>Coding style and formatting are pretty arbitrary, but a project is much easier to follow if everyone
uses the same style. Individuals may not agree with every aspect of the formatting rules, and
some of the rules may take some getting used to, but it is important that all project contributors
follow the style rules so that they can all read and understand everyone's code easily.</p>
<h3 id="Line_Length" style="left: -46px; position: relative;">Line Length</h3>
<div class="summary">
<p>Each line of text in your code should be at most 100 characters long.</p>
</div>
<div class="stylebody">
<p>We are innovative so we will not stick to the old 80-character limit.</p>
<div class="pros">
<p>Proponents argue that a wider line can make code more readable. The 80-column limit
is an hidebound throwback to 1960s mainframes; modern equipment has wide screens that can
easily show longer lines.</p>
<p>More focus on descriptive names also makes lines longer than they were in the past.</p>
</div>
<div class="cons">
<p>Those in favor of 80 characters argue that it is rude to force them to resize their windows and there
is no need for anything longer. Some folks are used to having several code windows side-by-side,
and thus don't have room to widen their windows in any case. People set up their work environment
assuming a particular maximum window width, and 80 columns has been the traditional standard.
Why change it?
</p>
</div>
<div class="decision">
<p> 100 characters is the maximum.</p>
<p class="exception">Comment lines can be longer than 100 characters if it is not feasible to split them without
harming readability, ease of cut and paste or auto-linking -- e.g. if a line contains an
example command or a literal URL longer than 100 characters.</p>
<p class="exception">A raw-string literal may have content that exceeds 100 characters. Except for test code, such
literals should appear near the top of a file.</p>
<p class="exception">An
<code>#include</code> statement with a long path may exceed 100 columns.</p>
<p class="exception">You needn't be concerned about
<a href="#The__define_Guard">header guards</a> that exceed the maximum length. </p>
</div>