blob: 48984bbdd9b2cc2faa6acb756a66f65d309aa697 [file] [log] [blame]
Alexander Afanasyev766cea72014-04-24 19:16:42 -07001ndn-cxx Code Style and Coding Guidelines
2========================================
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07003
4Based on
5
6 * "C++ Programming Style Guidelines" by Geotechnical Software Services, Copyright © 1996 – 2011.
7 The original document is available at `<http://geosoft.no/development/cppstyle.html>`_
8
9 * NDN Platform "C++, C, C#, Java and JavaScript Code Guidelines".
10 The original document available at `<http://named-data.net/codebase/platform/documentation/ndn-platform-development-guidelines/cpp-code-guidelines/>`_
11
Junxiao Shi28af1dc2014-11-06 15:53:32 -0700121. Code layout
13--------------
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -070014
151.1. The code layout should generally follow the GNU coding standard layout for C,
16extended it to C++.
17
18 * Do not use tabs for indentation.
19 * Indentation spacing is 2 spaces.
20 * Lines should be within a reasonable range. Lines longer than 100 columns should
21 generally be avoided.
22
231.2. Whitespace
24
25 * Conventional operators (``if``, ``for``, ``while``, and others) should be
26 surrounded by a space character.
27 * Commas should be followed by a white space.
28 * Semicolons in for statments should be followed by a space character.
29
30 Examples:
31
32 .. code-block:: c++
33
34 a = (b + c) * d; // NOT: a=(b+c)*d
35
36 while (true) { // NOT: while(true)
37 ...
38
39 doSomething(a, b, c, d); // NOT: doSomething(a,b,c,d);
40
41 for (i = 0; i < 10; i++) { // NOT: for(i=0;i<10;i++){
42 ...
43
441.3. Namespaces should have the following form:
45
46 .. code-block:: c++
47
48 namespace example {
49
50 code;
51 moreCode;
52
53 } // namespace example
54
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -050055 Note that code inside namespace is **not** indented. Avoid the following:
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -070056
57 .. code-block:: c++
58
59 // NOT
60 //
61 // namespace example {
62 //
63 // code;
64 // moreCode;
65 //
66 // } // namespace example
67
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500681.4. Class declarations should have the following form:
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -070069
70 .. code-block:: c++
71
72 class SomeClass : public BaseClass
73 {
74 public:
75 ... <public methods> ...
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -050076
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -070077 protected:
78 ... <protected methods> ...
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -050079
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -070080 private:
81 ... <private methods> ...
82
83 public:
84 ... <public data> ...
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -050085
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -070086 protected:
87 ... <protected data> ...
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -050088
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -070089 private:
90 ... <private data> ...
91 };
92
93 ``public``, ``protected``, ``private`` may be repeated several times without
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -050094 interleaving (e.g., public, public, public, private, private) if this improves
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -070095 readability of the code.
96
97 Nested classes can be defined in appropriate visibility section, either in methods
98 block, data block, or in a separate section (depending which one provides better code
99 readability).
100
1011.5. Method and function definitions should have the following form:
102
103 .. code-block:: c++
104
105 void
106 someMethod()
107 {
108 ...
109 }
110
111 void
112 SomeClass::someMethod()
113 {
114 ...
115 }
116
1171.6. The ``if-else`` class of statements should have the following form:
118
119 .. code-block:: c++
120
121 if (condition) {
122 statements;
123 }
124
125 if (condition) {
126 statements;
127 }
128 else {
129 statements;
130 }
131
132 if (condition) {
133 statements;
134 }
135 else if (condition) {
136 statements;
137 }
138 else {
139 statements;
140 }
141
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07001421.7. A ``for`` statement should have the following form:
143
144 .. code-block:: c++
145
146 for (initialization; condition; update) {
147 statements;
148 }
149
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500150 An empty ``for`` statement should have the following form:
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700151
152 .. code-block:: c++
153
154 for (initialization; condition; update)
155 ;
156
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500157 This emphasizes the fact that the ``for`` statement is empty and makes it obvious for
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700158 the reader that this is intentional. Empty loops should be avoided however.
159
1601.8. A ``while`` statement should have the following form:
161
162 .. code-block:: c++
163
164 while (condition) {
165 statements;
166 }
167
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07001681.9. A ``do-while`` statement should have the following form:
169
170 .. code-block:: c++
171
172 do {
173 statements;
174 } while (condition);
175
1761.10. A ``switch`` statement should have the following form:
177
178 .. code-block:: c++
179
180 switch (condition) {
Wentao Shang3aa4f412015-08-18 21:12:50 -0700181 case ABC: // 2 space indent
182 statements; // 4 space indent
Davide Pesavento1c597a12017-10-06 15:34:24 -0400183 NDN_CXX_FALLTHROUGH;
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700184
Wentao Shang3aa4f412015-08-18 21:12:50 -0700185 case DEF:
186 statements;
187 break;
188
189 case XYZ: {
190 statements;
191 break;
192 }
193
194 default:
195 statements;
196 break;
197 }
198
199 When curly braces are used inside a ``case`` block, the braces must cover the entire
200 ``case`` block.
201
202 .. code-block:: c++
203
204 switch (condition) {
205 // Correct style
206 case A0: {
207 statements;
208 break;
209 }
210
211 // Correct style
212 case A1: {
213 statements;
Davide Pesavento1c597a12017-10-06 15:34:24 -0400214 NDN_CXX_FALLTHROUGH;
Wentao Shang3aa4f412015-08-18 21:12:50 -0700215 }
216
217 // Incorrect style: braces should cover the entire case block
218 case B: {
219 statements;
220 }
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700221 statements;
222 break;
223
Wentao Shang3aa4f412015-08-18 21:12:50 -0700224 default:
225 break;
226 }
227
228 The following style is still allowed when none of the ``case`` blocks has curly braces.
229
230 .. code-block:: c++
231
232 switch (condition) {
233 case ABC: // no indent
234 statements; // 2 space indent
Davide Pesavento1c597a12017-10-06 15:34:24 -0400235 NDN_CXX_FALLTHROUGH;
Wentao Shang3aa4f412015-08-18 21:12:50 -0700236
237 case DEF:
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700238 statements;
239 break;
240
241 default:
242 statements;
243 break;
244 }
245
Davide Pesavento1c597a12017-10-06 15:34:24 -0400246 The ``NDN_CXX_FALLTHROUGH;`` annotation must be included whenever there is
247 a case without a break statement. Leaving the break out is a common error,
248 and it must be made clear that it is intentional when it is not there.
249 Moreover, modern compilers will warn when a case that falls through is not
250 explicitly annotated.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700251
2521.11. A ``try-catch`` statement should have the following form:
253
254 .. code-block:: c++
255
256 try {
257 statements;
258 }
Davide Pesaventocd183d22015-09-23 16:40:28 +0200259 catch (const Exception& exception) {
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700260 statements;
261 }
262
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07002631.12. The incompleteness of split lines must be made obvious.
264
265 .. code-block:: c++
266
267 totalSum = a + b + c +
268 d + e;
269 function(param1, param2,
270 param3);
271 for (int tableNo = 0; tableNo < nTables;
272 tableNo += tableStep) {
273 ...
274 }
275
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500276 Split lines occur when a statement exceeds the column limit given in rule 1.1. It is
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700277 difficult to give rigid rules for how lines should be split, but the examples above should
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500278 give a general hint. In general:
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700279
280 * Break after a comma.
281 * Break after an operator.
282 * Align the new line with the beginning of the expression on the previous line.
283
284 Exceptions:
285
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500286 * The following is standard practice with ``operator<<``:
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700287
288 .. code-block:: c++
289
290 std::cout << "Something here "
291 << "Something there" << std::endl;
292
2931.13. When class variables need to be initialized in the constructor, the initialization
294should take the following form:
295
296 .. code-block:: c++
297
298 SomeClass::SomeClass(int value, const std::string& string)
299 : m_value(value)
300 , m_string(string)
301 ...
302 {
303 }
304
305 Each initialization should be put on a separate line, starting either with the colon
306 for the first initialization or with comma for all subsequent initializations.
307
Junxiao Shi45c13842014-11-02 15:36:04 -07003081.14. A range-based ``for`` statement should have the following form:
309
310 .. code-block:: c++
311
312 for (T i : range) {
313 statements;
314 }
315
Junxiao Shicf698182014-11-03 08:37:42 -07003161.15. A lambda expression should have the following form:
317
318 .. code-block:: c++
319
320 [&capture1, capture2] (T1 arg1, T2 arg2) {
321 statements;
322 }
323
324 [&capture1, capture2] (T1 arg1, T2 arg2) mutable {
325 statements;
326 }
327
328 [this] (T arg) {
329 statements;
330 }
331
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500332 If the lambda has no parameters, ``()`` should be omitted.
Junxiao Shicf698182014-11-03 08:37:42 -0700333
334 .. code-block:: c++
335
336 [&capture1, capture2] {
337 statements;
338 }
339
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500340 Either capture-default (``[&]`` or ``[=]``) is permitted, but its usage should be minimized.
341 Only use a capture-default when it significantly simplifies code and improves readability.
Junxiao Shicf698182014-11-03 08:37:42 -0700342
343 .. code-block:: c++
344
345 [&] (T arg) {
346 statements;
347 }
348
349 [=] (T arg) {
350 statements;
351 }
352
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500353 Trailing return type should be omitted whenever possible. Add it only when the compiler
354 cannot deduce the return type automatically, or when it improves readability.
355 ``()`` is required by the C++ standard when ``mutable`` or a trailing return type is used.
Junxiao Shicf698182014-11-03 08:37:42 -0700356
357 .. code-block:: c++
358
359 [] (T arg) -> int {
360 statements;
361 }
362
363 [] () -> int {
364 statements;
365 }
366
367 If the function body has only one line, and the whole lambda expression can fit in one line,
368 the following form is also acceptable:
369
370 .. code-block:: c++
371
372 [&capture1, capture2] (T1 arg1, T2 arg2) { statement; }
373
374 No-op can be written in a more compact form:
375
376 .. code-block:: c++
377
378 []{}
379
Junxiao Shi8b12a5a2014-11-25 10:42:47 -07003801.16. List initialization should have the following form:
381
382 .. code-block:: c++
383
384 T object{arg1, arg2};
385
386 T{arg1, arg2};
387
388 new T{arg1, arg2};
389
390 return {arg1, arg2};
391
392 function({arg1, arg2}, otherArgument);
393
394 object[{arg1, arg2}];
395
396 T({arg1, arg2})
397
398 class Class
399 {
400 private:
Davide Pesaventoe6e6fde2016-04-16 14:44:45 +0200401 T m_member = {arg1, arg2};
Junxiao Shi8b12a5a2014-11-25 10:42:47 -0700402 static T s_member = {arg1, arg2};
403 };
404
405 Class::Class()
406 : m_member{arg1, arg2}
407 {
408 }
409
410 T object = {arg1, arg2};
411
412 An empty braced-init-list is written as ``{}``. For example:
413
414 .. code-block:: c++
415
416 T object{};
417
418 T object = {};
419
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07004202. Naming Conventions
421---------------------
422
4232.1. C++ header files should have the extension ``.hpp``. Source files should have the
424extension ``.cpp``
425
426 File names should be all lower case. If the class name
427 is a composite of several words, each word in a file name should be separated with a
428 dash (-). A class should be declared in a header file and defined in a source file
429 where the name of the files match the name of the class.
430
431 ::
432
433 my-class.hpp, my-class.cpp
434
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07004352.2. Names representing types must be written in English in mixed case starting with upper case.
436
437 .. code-block:: c++
438
439 class MyClass;
440 class Line;
441 class SavingsAccount;
442
4432.3. Variable names must be written in English in mixed case starting with lower case.
444
445 .. code-block:: c++
446
447 MyClass myClass;
448 Line line;
449 SavingsAccount savingsAccount;
450 int theAnswerToLifeTheUniverseAndEverything;
451
4522.4. Named constants (including enumeration values) must be all uppercase using underscore
453to separate words.
454
455 .. code-block:: c++
456
457 const int MAX_ITERATIONS = 25;
458 const std::string COLOR_RED = "red";
459 static const double PI = 3.14;
460
461 In some cases, it is a better (or is the only way for complex constants in header-only
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500462 classes) to implement the value as a method.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700463
464 .. code-block:: c++
465
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500466 static int // declare constexpr if possible
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700467 getMaxIterations()
468 {
469 return 25;
470 }
471
4722.5. Names representing methods or functions must be commands starting with a verb and
473written in mixed case starting with lower case.
474
475 .. code-block:: c++
476
477 std::string
478 getName()
479 {
480 ...
481 }
482
483 double
484 computeTotalWidth()
485 {
486 ...
487 }
488
4892.6. Names representing namespaces should be all lowercase.
490
491 .. code-block:: c++
492
493 namespace model {
494 namespace analyzer {
495
496 ...
497
498 } // namespace analyzer
499 } // namespace model
500
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -05005012.7. Names representing generic template types should be a single uppercase letter.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700502
503 .. code-block:: c++
504
505 template<class T> ...
506 template<class C, class D> ...
507
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500508 However, when a template parameter represents a certain concept and is expected
509 to have a certain interface, the name should be explicitly spelled out.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700510
511 .. code-block:: c++
512
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500513 template<class InputIterator> ...
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700514 template<class Packet> ...
515
5162.8. Abbreviations and acronyms must not be uppercase when used as name.
517
518 .. code-block:: c++
519
520 exportHtmlSource(); // NOT: exportHTMLSource();
521 openDvdPlayer(); // NOT: openDVDPlayer();
522
5232.9. Global variables should have ``g_`` prefix
524
525 .. code-block:: c++
526
527 g_mainWindow.open();
528 g_applicationContext.getName();
529
530 In general, the use of global variables should be avoided. Consider using singleton
531 objects instead.
532
5332.10. Private class variables should have ``m_`` prefix. Static class variables should have
534``s_`` prefix.
535
536 .. code-block:: c++
537
538 class SomeClass
539 {
540 private:
541 int m_length;
542
543 static std::string s_name;
544 };
545
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07005462.11. Variables with a large scope should have long (explicit) names, variables with a small
547scope can have short names.
548
549 Scratch variables used for temporary storage or indices are best kept short. A
550 programmer reading such variables should be able to assume that its value is not used
551 outside of a few lines of code. Common scratch variables for integers are ``i``,
552 ``j``, ``k``, ``m``, ``n`` and for characters ``c`` and ``d``.
553
5542.12. The name of the object is implicit, and should be avoided in a method name.
555
556 .. code-block:: c++
557
558 line.getLength(); // NOT: line.getLineLength();
559
560 The latter seems natural in the class declaration, but proves superfluous in use, as
561 shown in the example.
562
5632.13. The terms ``get/set`` must be used where an attribute is accessed directly.
564
565 .. code-block:: c++
566
567 employee.getName();
568 employee.setName(name);
569
570 matrix.getElement(2, 4);
571 matrix.setElement(2, 4, value);
572
5732.14. The term ``compute`` can be used in methods where something is computed.
574
575 .. code-block:: c++
576
577 valueSet.computeAverage();
578 matrix.computeInverse()
579
580 Give the reader the immediate clue that this is a potentially time-consuming operation,
581 and if used repeatedly, he might consider caching the result. Consistent use of the term
582 enhances readability.
583
5842.15. The term ``find`` can be used in methods where something is looked up.
585
586 .. code-block:: c++
587
588 vertex.findNearestVertex();
589 matrix.findMinElement();
590
591 Give the reader the immediate clue that this is a simple look up method with a minimum
592 of computations involved. Consistent use of the term enhances readability.
593
5942.16. Plural form should be used on names representing a collection of objects.
595
596 .. code-block:: c++
597
598 vector<Point> points;
599 int values[];
600
601 Enhances readability since the name gives the user an immediate clue of the type of
602 the variable and the operations that can be performed on its elements.
603
6042.17. The prefix ``n`` should be used for variables representing a number of objects.
605
606 .. code-block:: c++
607
608 nPoints, nLines
609
610 The notation is taken from mathematics where it is an established convention for
611 indicating a number of objects.
612
Eric Newberry436e46f2018-06-10 21:45:57 -07006132.18. The suffix ``Num`` or ``No`` should be used for variables representing an entity number.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700614
615 .. code-block:: c++
616
Eric Newberry436e46f2018-06-10 21:45:57 -0700617 tableNum, tableNo, employeeNum, employeeNo
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700618
6192.19. The prefix ``is``, ``has``, ``need``, or similar should be used for boolean variables and
620methods.
621
622 .. code-block:: c++
623
624 isSet, isVisible, isFinished, isFound, isOpen
625 needToConvert, needToFinish
626
6272.20. Complement names must be used for complement operations, reducing complexity by
628symmetry.
629
630 ::
631
632 get/set, add/remove, create/destroy, start/stop, insert/delete,
633 increment/decrement, old/new, begin/end, first/last, up/down, min/max,
634 next/previous (and commonly used next/prev), open/close, show/hide,
635 suspend/resume, etc.
636
637 Pair ``insert/erase`` should be preferred. ``insert/delete`` can also be used if it
638 does not conflict with C++ delete keyword.
639
6402.21. Variable names should not include reference to variable type (do not use Hungarian
641notation).
642
643 .. code-block:: c++
644
645 Line* line; // NOT: Line* pLine;
646 // NOT: Line* linePtr;
647
648 size_t nPoints; // NOT lnPoints
649
650 char* name; // NOT szName
651
6522.22. Negated boolean variable names should be avoided.
653
654 .. code-block:: c++
655
656 bool isError; // NOT: isNoError
657 bool isFound; // NOT: isNotFound
658
6592.23. Enumeration constants recommended to prefix with a common type name.
660
661 .. code-block:: c++
662
663 enum Color {
664 COLOR_RED,
665 COLOR_GREEN,
666 COLOR_BLUE
667 };
668
6692.24. Exceptions can be suffixed with either ``Exception`` (e.g., ``SecurityException``) or
670``Error`` (e.g., ``SecurityError``).
671
672 The recommended method is to declare exception class ``Exception`` or ``Error`` as an
673 inner class, from which the exception is thrown. For example, when declaring class
674 ``Foo`` that can throw errors, one can write the following:
675
676 .. code-block:: c++
677
678 #include <stdexcept>
679
680 class Foo
681 {
Junxiao Shi68b53852018-07-25 13:56:38 -0600682 public:
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700683 class Error : public std::runtime_error
684 {
685 public:
Junxiao Shi68b53852018-07-25 13:56:38 -0600686 // You can inherit constructors from std::runtime_error like this:
687 using std::runtime_error::runtime_error;
688
689 // Additional constructors, if desired, can be declared like this:
690 Error(const std::string& what, const std::exception& inner)
691 : std::runtime_error(what + ": " + inner.what())
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700692 {
693 }
694 };
695 };
696
697 In addition to that, if class Foo is a base class or interface for some class
698 hierarchy, then child classes should should define their own ``Error`` or
699 ``Exception`` classes that are inherited from the parent's Error class.
700
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07007012.25. Functions (methods returning something) should be named after what they return and
702procedures (void methods) after what they do.
703
704 Increase readability. Makes it clear what the unit should do and especially all the
705 things it is not supposed to do. This again makes it easier to keep the code clean of
706 side effects.
707
7083. Miscellaneous
709----------------
710
7113.1. Exceptions can be used in the code, but should be used only in exceptional cases and
712not in the primary processing path.
713
7143.2. Header files must contain an include guard.
715
Davide Pesavento7e780642018-11-24 15:51:34 -0500716 For example, a header file named ``module/class-name.hpp`` or
717 ``src/module/class-name.hpp`` should have a header guard in the following form:
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700718
719 .. code-block:: c++
720
721 #ifndef APP_MODULE_CLASS_NAME_HPP
722 #define APP_MODULE_CLASS_NAME_HPP
723 ...
724 #endif // APP_MODULE_CLASS_NAME_HPP
725
Davide Pesavento7e780642018-11-24 15:51:34 -0500726 The macro name should reflect the path of the header file relative to the root of the
727 source tree, in order to prevent naming conflicts. The header guard should be prefixed
728 with the application/library name to avoid conflicts with other packages and libraries.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700729
Davide Pesavento7e780642018-11-24 15:51:34 -05007303.3. Include directives for system headers and other external libraries should use
731``<angle brackets>``. Header files in the same source code repository should be included
732using ``"quotes"``.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700733
734 .. code-block:: c++
735
Davide Pesavento7e780642018-11-24 15:51:34 -0500736 #include "ndn-cxx/util/random.hpp"
737
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700738 #include <string>
739 #include <boost/lexical_cast.hpp>
740
Davide Pesavento7e780642018-11-24 15:51:34 -0500741 All of a project's header files should be included with their path relative to
742 the project's source directory. The use of UNIX directory shortcuts ``.``
743 (the current directory) and ``..`` (the parent directory) is discouraged.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700744
Junxiao Shi4f92d872017-07-25 22:04:48 +00007453.4. Include statements should be grouped. Same-project headers should be included first.
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500746Leave an empty line between groups of include statements. Sort alphabetically within a group.
Davide Pesavento7e780642018-11-24 15:51:34 -0500747For example, the include section of ``ndn-cxx/foo/bar.cpp`` may look like this:
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700748
749 .. code-block:: c++
750
Davide Pesavento7e780642018-11-24 15:51:34 -0500751 #include "ndn-cxx/detail/pending-interest.hpp"
752 #include "ndn-cxx/util/random.hpp"
Junxiao Shi4f92d872017-07-25 22:04:48 +0000753
Davide Pesavento7e780642018-11-24 15:51:34 -0500754 #include <cstdlib>
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700755 #include <fstream>
756 #include <iomanip>
757
758 #include <boost/lexical_cast.hpp>
759 #include <boost/regex.hpp>
760
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07007613.5. Types that are local to one file only can be declared inside that file.
762
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07007633.6. Implicit conversion is generally allowed.
764
765 Implicit conversion between integer and floating point numbers can cause problems and
766 should be avoided.
767
768 Implicit conversion in single-argument constructor is usually undesirable. Therefore, all
769 single-argument constructors should be marked 'explicit', unless implicit conversion is
770 desirable. In that case, a comment should document the reason.
771
772 Avoid C-style casts. Use ``static_cast``, ``dynamic_cast``, ``reinterpret_cast``,
773 ``const_cast`` instead where appropriate. Use ``static_pointer_cast``,
774 ``dynamic_pointer_cast``, ``const_pointer_cast`` when dealing with ``shared_ptr``.
775
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07007763.7. Variables should be initialized where they are declared.
777
778 This ensures that variables are valid at any time. Sometimes it is impossible to
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500779 initialize a variable to a valid value where it is declared.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700780
781 .. code-block:: c++
782
783 int x, y, z;
784 getCenter(&x, &y, &z);
785
786 In these cases it should be left uninitialized rather than initialized to some phony
787 value.
788
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -05007893.8. In most cases, class data members should not be declared ``public``.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700790
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500791 Public data members violate the concepts of information hiding and encapsulation.
792 Use private variables and public accessor methods instead.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700793
794 Exceptions to this rule:
795
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500796 * When the class is essentially a dumb data structure with no or minimal behavior
797 (equivalent to a C struct, also known as POD type). In this case it is appropriate
798 to make the instance variables public by using ``struct``.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700799
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500800 * When the class is used only inside the compilation unit, e.g., when implementing pImpl
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700801 idiom (aka Bridge pattern) or similar cases.
802
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07008033.9. C++ pointers and references should have their reference symbol next to the type rather
804than to the name.
805
806 .. code-block:: c++
807
808 float* x; // NOT: float *x;
809 int& y; // NOT: int &y;
810
8113.10. Implicit test for 0 should not be used other than for boolean variables and pointers.
812
813 .. code-block:: c++
814
815 if (nLines != 0) // NOT: if (nLines)
816 if (value != 0.0) // NOT: if (value)
817
Davide Pesaventobbca1b92015-12-25 20:06:00 +01008183.11. *(removed)*
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700819
8203.12. Loop variables should be initialized immediately before the loop.
821
822 .. code-block:: c++
823
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500824 bool isDone = false; // NOT: bool isDone = false;
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700825 while (!isDone) { // // other stuff
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500826 ... // while (!isDone) {
827 } // ...
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700828 // }
829
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -05008303.13. The form ``while (true)`` should be used for infinite loops.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700831
832 .. code-block:: c++
833
834 while (true) {
835 ...
836 }
837
838 // NOT:
839 for (;;) { // NO!
840 :
841 }
842 while (1) { // NO!
843 :
844 }
845
8463.14. Complex conditional expressions must be avoided. Introduce temporary boolean variables
847instead.
848
849 .. code-block:: c++
850
851 bool isFinished = (elementNo < 0) || (elementNo > maxElement);
852 bool isRepeatedEntry = elementNo == lastElement;
853 if (isFinished || isRepeatedEntry) {
854 ...
855 }
856
857 // NOT:
858 // if ((elementNo < 0) || (elementNo > maxElement) || elementNo == lastElement) {
859 // ...
860 // }
861
862 By assigning boolean variables to expressions, the program gets automatic
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500863 documentation. The construction will be easier to read, debug, and maintain.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700864
8653.15. The conditional should be put on a separate line.
866
867 .. code-block:: c++
868
869 if (isDone) // NOT: if (isDone) doCleanup();
870 doCleanup();
871
872 This is for debugging purposes. When writing on a single line, it is not apparent
873 whether the test is really true or not.
874
8753.16. Assignment statements in conditionals must be avoided.
876
877 .. code-block:: c++
878
879 File* fileHandle = open(fileName, "w");
880 if (!fileHandle) {
881 ...
882 }
883
884 // NOT
885 // if (!(fileHandle = open(fileName, "w"))) {
886 // ..
887 // }
888
8893.17. The use of magic numbers in the code should be avoided. Numbers other than 0 and 1
890should be considered declared as named constants instead.
891
892 If the number does not have an obvious meaning by itself, the readability is enhanced
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500893 by introducing a named constant instead. A different approach is to introduce a method
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700894 from which the constant can be accessed.
895
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -05008963.18. Floating point literals should always be written with a decimal point, at least one
897decimal, and without omitting 0 before the decimal point.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700898
899 .. code-block:: c++
900
901 double total = 0.0; // NOT: double total = 0;
902 double someValue = 0.1; // NOT double someValue = .1;
903 double speed = 3.0e8; // NOT: double speed = 3e8;
904 double sum;
905 ...
906 sum = (a + b) * 10.0;
907
9083.19. ``goto`` should not be used.
909
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500910 ``goto`` statements violate the idea of structured code. Only in very few cases (for
911 instance, breaking out of deeply nested structures) should ``goto`` be considered,
912 and only if the alternative structured counterpart is proven to be less readable.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700913
Junxiao Shi03b15b32014-10-30 21:10:25 -07009143.20. ``nullptr`` should be used to represent a null pointer, instead of "0" or "NULL".
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700915
9163.21. Logical units within a block should be separated by one blank line.
917
918 .. code-block:: c++
919
920 Matrix4x4 matrix = new Matrix4x4();
921
922 double cosAngle = Math.cos(angle);
923 double sinAngle = Math.sin(angle);
924
925 matrix.setElement(1, 1, cosAngle);
926 matrix.setElement(1, 2, sinAngle);
927 matrix.setElement(2, 1, -sinAngle);
928 matrix.setElement(2, 2, cosAngle);
929
930 multiply(matrix);
931
932 Enhance readability by introducing white space between logical units of a block.
933
9343.22. Variables in declarations can be left aligned.
935
936 .. code-block:: c++
937
938 AsciiFile* file;
939 int nPoints;
940 float x, y;
941
942 Enhance readability. The variables are easier to spot from the types by alignment.
943
9443.23. Use alignment wherever it enhances readability.
945
946 .. code-block:: c++
947
948 value = (potential * oilDensity) / constant1 +
949 (depth * waterDensity) / constant2 +
950 (zCoordinateValue * gasDensity) / constant3;
951
952 minPosition = computeDistance(min, x, y, z);
953 averagePosition = computeDistance(average, x, y, z);
954
955 There are a number of places in the code where white space can be included to enhance
956 readability even if this violates common guidelines. Many of these cases have to do
957 with code alignment. General guidelines on code alignment are difficult to give, but
958 the examples above should give a general clue.
959
9603.24. All comments should be written in English.
961
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500962 In an international environment, English is the preferred language.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700963
Alexander Afanasyevdfa52c42014-04-24 21:10:11 -07009643.25. Use ``//`` for all comments, including multi-line comments.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700965
966 .. code-block:: c++
967
968 // Comment spanning
969 // more than one line.
970
971 Since multilevel C-commenting is not supported, using ``//`` comments ensure that it
972 is always possible to comment out entire sections of a file using ``/* */`` for
973 debugging purposes etc.
974
975 There should be a space between the ``//`` and the actual comment, and comments should
976 always start with an upper case letter and end with a period.
977
978 However, method and class documentation comments should use ``/** */`` style for
Junxiao Shibd2cedb2017-07-05 18:51:52 +0000979 Doxygen, JavaDoc and JSDoc. License boilerplate should use ``/* */`` style.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700980
9813.26. Comments should be included relative to their position in the code.
982
983 .. code-block:: c++
984
985 while (true) {
986 // Do something
987 something();
988 }
989
990 // NOT:
991 while (true) {
992 // Do something
993 something();
994 }
995
996 This is to avoid that the comments break the logical structure of the program.
Junxiao Shiae61aac2014-11-04 14:57:38 -0700997
9983.27. Use ``BOOST_ASSERT`` and ``BOOST_ASSERT_MSG`` for runtime assertions.
999
1000 .. code-block:: c++
1001
1002 int x = 1;
1003 int y = 2;
1004 int z = x + y;
1005 BOOST_ASSERT(z - y == x);
1006
1007 The expression passed to ``BOOST_ASSERT`` MUST NOT have side effects,
1008 because it MAY NOT be evaluated in release builds.
1009
10103.28. Use ``static_assert`` for static assertions.
1011
Junxiao Shiae61aac2014-11-04 14:57:38 -07001012 .. code-block:: c++
1013
1014 class BaseClass
1015 {
1016 };
1017
1018 class DerivedClass : public BaseClass
1019 {
1020 };
1021
1022 static_assert(std::is_base_of<BaseClass, DerivedClass>::value,
1023 "DerivedClass must inherit from BaseClass");
Junxiao Shic0a8c3b2014-11-08 12:09:05 -07001024
10253.29. ``auto`` type specifier MAY be used for local variables, if a human reader
1026 can easily deduce the actual type.
1027
1028 .. code-block:: c++
1029
1030 std::vector<int> intVector;
1031 auto i = intVector.find(4);
1032
1033 auto stringSet = std::make_shared<std::set<std::string>>();
1034
1035 ``auto`` SHOULD NOT be used if a human reader cannot easily deduce the actual type.
1036
1037 .. code-block:: c++
1038
1039 auto x = foo(); // BAD if the declaration of foo() isn't nearby
1040
1041 ``const auto&`` SHOULD be used to represent constant reference types.
1042 ``auto&&`` SHOULD be used to represent mutable reference types.
1043
1044 .. code-block:: c++
1045
1046 std::list<std::string> strings;
Junxiao Shic0a8c3b2014-11-08 12:09:05 -07001047 for (const auto& str : strings) {
1048 statements; // cannot modify `str`
1049 }
1050 for (auto&& str : strings) {
1051 statements; // can modify `str`
1052 }
Junxiao Shia76bbc92015-03-23 11:05:37 -07001053
Davide Pesaventode2a1c22016-12-11 15:46:13 -050010543.30. Use the ``override`` or ``final`` specifier when overriding a virtual
1055member function or a virtual destructor.
Junxiao Shia76bbc92015-03-23 11:05:37 -07001056
Davide Pesaventode2a1c22016-12-11 15:46:13 -05001057 ``virtual`` MUST NOT be used along with ``final``, so that the compiler
1058 can generate an error when a final function does not override.
1059
1060 ``virtual`` SHOULD NOT be used along with ``override``, for consistency
1061 with ``final``.
Junxiao Shia76bbc92015-03-23 11:05:37 -07001062
1063 .. code-block:: c++
1064
1065 class Stream
1066 {
1067 public:
1068 virtual void
1069 open();
1070 };
1071
1072 class InputStream : public Stream
1073 {
1074 public:
Davide Pesaventode2a1c22016-12-11 15:46:13 -05001075 void
Junxiao Shia76bbc92015-03-23 11:05:37 -07001076 open() override;
1077 };
1078
1079 class Console : public InputStream
1080 {
1081 public:
Davide Pesaventode2a1c22016-12-11 15:46:13 -05001082 void
1083 open() final;
Junxiao Shia76bbc92015-03-23 11:05:37 -07001084 };
1085
Spyridon Mastorakis0d2ed2e2015-07-27 19:09:12 -070010863.31. The recommended way to throw an exception derived from ``std::exception`` is to use
1087the ``BOOST_THROW_EXCEPTION``
Davide Pesavento844b0932018-05-07 01:00:16 -04001088`macro <https://www.boost.org/doc/libs/1_58_0/libs/exception/doc/BOOST_THROW_EXCEPTION.html>`__.
Davide Pesaventobbca1b92015-12-25 20:06:00 +01001089Exceptions thrown using this macro will be augmented with additional diagnostic information,
1090including file name, line number, and function name from where the exception was thrown.