blob: 131d48a746154e35d1ebb3e71335ff5d2ed924d6 [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
Davide Pesavento47ce2ee2023-05-09 01:33:33 -04006* "C++ Programming Style Guidelines" by Geotechnical Software Services, Copyright © 1996-2011.
7 The original document is available at `<http://geosoft.no/development/cppstyle.html>`__
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07008
Davide Pesavento0b2aa132020-12-11 23:00:02 -05009* NDN Platform "C++, C, C#, Java and JavaScript Code Guidelines".
Davide Pesavento47ce2ee2023-05-09 01:33:33 -040010 The original document is available at `<https://named-data.net/codebase/platform/documentation/ndn-platform-development-guidelines/cpp-code-guidelines/>`__
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -070011
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
Davide Pesavento0b2aa132020-12-11 23:00:02 -050034 a = (b + c) * d; // NOT: a=(b+c)*d
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -070035
Davide Pesavento0b2aa132020-12-11 23:00:02 -050036 while (true) { // NOT: while(true)
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -070037 ...
38
Davide Pesavento0b2aa132020-12-11 23:00:02 -050039 doSomething(a, b, c, d); // NOT: doSomething(a,b,c,d);
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -070040
Davide Pesavento0b2aa132020-12-11 23:00:02 -050041 for (i = 0; i < 10; i++) { // NOT: for(i=0;i<10;i++){
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -070042 ...
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 Pesavento47ce2ee2023-05-09 01:33:33 -040055 Note that code inside the namespace is **not** indented. Avoid the following:
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -070056
57 .. code-block:: c++
58
Davide Pesavento28530b62025-05-07 13:22:21 -040059 // WRONG!
60
61 namespace example {
62
63 code;
64 moreCode;
65
66 } // namespace example
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -070067
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 Pesaventofcd3e442023-03-10 18:44:11 -0500183 [[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 Pesaventofcd3e442023-03-10 18:44:11 -0500214 [[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 Pesaventofcd3e442023-03-10 18:44:11 -0500235 [[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 Pesaventofcd3e442023-03-10 18:44:11 -0500246 The ``[[fallthrough]]`` annotation must be included whenever there is a
247 case without a break statement. Leaving the break out is a common error,
Davide Pesavento1c597a12017-10-06 15:34:24 -0400248 and it must be made clear that it is intentional when it is not there.
Davide Pesaventofcd3e442023-03-10 18:44:11 -0500249 Moreover, modern compilers will warn when a case that falls through is
250 not 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
Davide Pesavento28530b62025-05-07 13:22:21 -0400288 .. code-block:: c++
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700289
Davide Pesavento28530b62025-05-07 13:22:21 -0400290 std::cout << "Something here "
291 << "Something there" << std::endl;
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700292
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
Junxiao Shicf698182014-11-03 08:37:42 -0700332 [&] (T arg) {
333 statements;
334 }
335
336 [=] (T arg) {
337 statements;
338 }
339
Davide Pesavento0b2aa132020-12-11 23:00:02 -0500340 If the lambda has no parameters, ``()`` should be omitted.
341
342 .. code-block:: c++
343
344 [&capture1, capture2] {
345 statements;
346 }
347
348 Trailing return types should be omitted whenever possible. Add it only when the compiler
349 cannot deduce the return type automatically, or when it improves readability. Note that
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500350 ``()`` is required by the C++ standard when ``mutable`` or a trailing return type is used.
Junxiao Shicf698182014-11-03 08:37:42 -0700351
352 .. code-block:: c++
353
354 [] (T arg) -> int {
355 statements;
356 }
357
358 [] () -> int {
359 statements;
360 }
361
362 If the function body has only one line, and the whole lambda expression can fit in one line,
363 the following form is also acceptable:
364
365 .. code-block:: c++
366
367 [&capture1, capture2] (T1 arg1, T2 arg2) { statement; }
368
Davide Pesavento0b2aa132020-12-11 23:00:02 -0500369 A no-op lambda can be written in a more compact form:
Junxiao Shicf698182014-11-03 08:37:42 -0700370
371 .. code-block:: c++
372
373 []{}
374
Junxiao Shi8b12a5a2014-11-25 10:42:47 -07003751.16. List initialization should have the following form:
376
377 .. code-block:: c++
378
379 T object{arg1, arg2};
380
381 T{arg1, arg2};
382
383 new T{arg1, arg2};
384
385 return {arg1, arg2};
386
387 function({arg1, arg2}, otherArgument);
388
389 object[{arg1, arg2}];
390
391 T({arg1, arg2})
392
Davide Pesavento0b2aa132020-12-11 23:00:02 -0500393 T object = {arg1, arg2};
394
Junxiao Shi8b12a5a2014-11-25 10:42:47 -0700395 class Class
396 {
397 private:
Davide Pesavento0b2aa132020-12-11 23:00:02 -0500398 T m_member{arg1, arg2};
Junxiao Shi8b12a5a2014-11-25 10:42:47 -0700399 static T s_member = {arg1, arg2};
400 };
401
Junxiao Shi8b12a5a2014-11-25 10:42:47 -0700402 An empty braced-init-list is written as ``{}``. For example:
403
404 .. code-block:: c++
405
406 T object{};
Junxiao Shi8b12a5a2014-11-25 10:42:47 -0700407 T object = {};
408
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07004092. Naming Conventions
410---------------------
411
4122.1. C++ header files should have the extension ``.hpp``. Source files should have the
Davide Pesavento28530b62025-05-07 13:22:21 -0400413extension ``.cpp``. File names should be all lower case. If the class name is a composite
414of several words, each word in a file name should be separated with a dash (``-``).
415A class should be declared in a header file and defined in a source file where the name
416of the files match the name of the class. Example file names::
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700417
Davide Pesavento28530b62025-05-07 13:22:21 -0400418 my-class.hpp
419 my-class.cpp
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700420
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07004212.2. Names representing types must be written in English in mixed case starting with upper case.
422
423 .. code-block:: c++
424
425 class MyClass;
426 class Line;
427 class SavingsAccount;
428
4292.3. Variable names must be written in English in mixed case starting with lower case.
430
431 .. code-block:: c++
432
433 MyClass myClass;
434 Line line;
435 SavingsAccount savingsAccount;
436 int theAnswerToLifeTheUniverseAndEverything;
437
4382.4. Named constants (including enumeration values) must be all uppercase using underscore
439to separate words.
440
441 .. code-block:: c++
442
443 const int MAX_ITERATIONS = 25;
444 const std::string COLOR_RED = "red";
445 static const double PI = 3.14;
446
447 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 -0500448 classes) to implement the value as a method.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700449
450 .. code-block:: c++
451
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500452 static int // declare constexpr if possible
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700453 getMaxIterations()
454 {
455 return 25;
456 }
457
4582.5. Names representing methods or functions must be commands starting with a verb and
459written in mixed case starting with lower case.
460
461 .. code-block:: c++
462
463 std::string
464 getName()
465 {
466 ...
467 }
468
469 double
470 computeTotalWidth()
471 {
472 ...
473 }
474
4752.6. Names representing namespaces should be all lowercase.
476
477 .. code-block:: c++
478
Davide Pesavento47ce2ee2023-05-09 01:33:33 -0400479 namespace model::analyzer {
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700480
481 ...
482
Davide Pesavento47ce2ee2023-05-09 01:33:33 -0400483 } // namespace model::analyzer
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700484
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -05004852.7. Names representing generic template types should be a single uppercase letter.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700486
487 .. code-block:: c++
488
489 template<class T> ...
490 template<class C, class D> ...
491
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500492 However, when a template parameter represents a certain concept and is expected
493 to have a certain interface, the name should be explicitly spelled out.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700494
495 .. code-block:: c++
496
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500497 template<class InputIterator> ...
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700498 template<class Packet> ...
499
5002.8. Abbreviations and acronyms must not be uppercase when used as name.
501
502 .. code-block:: c++
503
504 exportHtmlSource(); // NOT: exportHTMLSource();
505 openDvdPlayer(); // NOT: openDVDPlayer();
506
5072.9. Global variables should have ``g_`` prefix
508
509 .. code-block:: c++
510
511 g_mainWindow.open();
512 g_applicationContext.getName();
513
514 In general, the use of global variables should be avoided. Consider using singleton
515 objects instead.
516
Davide Pesavento0b2aa132020-12-11 23:00:02 -05005172.10. All non-static data members of a class should be prefixed with ``m_`` unless they
518are public. Similarly, non-public static data members should be prefixed with ``s_``.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700519
520 .. code-block:: c++
521
522 class SomeClass
523 {
524 private:
525 int m_length;
526
527 static std::string s_name;
528 };
529
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07005302.11. Variables with a large scope should have long (explicit) names, variables with a small
531scope can have short names.
532
533 Scratch variables used for temporary storage or indices are best kept short. A
534 programmer reading such variables should be able to assume that its value is not used
535 outside of a few lines of code. Common scratch variables for integers are ``i``,
536 ``j``, ``k``, ``m``, ``n`` and for characters ``c`` and ``d``.
537
5382.12. The name of the object is implicit, and should be avoided in a method name.
539
540 .. code-block:: c++
541
542 line.getLength(); // NOT: line.getLineLength();
543
544 The latter seems natural in the class declaration, but proves superfluous in use, as
545 shown in the example.
546
5472.13. The terms ``get/set`` must be used where an attribute is accessed directly.
548
549 .. code-block:: c++
550
551 employee.getName();
552 employee.setName(name);
553
554 matrix.getElement(2, 4);
555 matrix.setElement(2, 4, value);
556
5572.14. The term ``compute`` can be used in methods where something is computed.
558
559 .. code-block:: c++
560
561 valueSet.computeAverage();
562 matrix.computeInverse()
563
564 Give the reader the immediate clue that this is a potentially time-consuming operation,
565 and if used repeatedly, he might consider caching the result. Consistent use of the term
566 enhances readability.
567
5682.15. The term ``find`` can be used in methods where something is looked up.
569
570 .. code-block:: c++
571
572 vertex.findNearestVertex();
573 matrix.findMinElement();
574
575 Give the reader the immediate clue that this is a simple look up method with a minimum
576 of computations involved. Consistent use of the term enhances readability.
577
5782.16. Plural form should be used on names representing a collection of objects.
579
580 .. code-block:: c++
581
582 vector<Point> points;
583 int values[];
584
585 Enhances readability since the name gives the user an immediate clue of the type of
586 the variable and the operations that can be performed on its elements.
587
5882.17. The prefix ``n`` should be used for variables representing a number of objects.
589
590 .. code-block:: c++
591
592 nPoints, nLines
593
594 The notation is taken from mathematics where it is an established convention for
595 indicating a number of objects.
596
Eric Newberry436e46f2018-06-10 21:45:57 -07005972.18. The suffix ``Num`` or ``No`` should be used for variables representing an entity number.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700598
599 .. code-block:: c++
600
Eric Newberry436e46f2018-06-10 21:45:57 -0700601 tableNum, tableNo, employeeNum, employeeNo
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700602
6032.19. The prefix ``is``, ``has``, ``need``, or similar should be used for boolean variables and
604methods.
605
606 .. code-block:: c++
607
608 isSet, isVisible, isFinished, isFound, isOpen
609 needToConvert, needToFinish
610
6112.20. Complement names must be used for complement operations, reducing complexity by
612symmetry.
613
614 ::
615
Davide Pesavento0b2aa132020-12-11 23:00:02 -0500616 get/set, add/remove, create/destroy, start/stop, insert/erase,
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700617 increment/decrement, old/new, begin/end, first/last, up/down, min/max,
618 next/previous (and commonly used next/prev), open/close, show/hide,
619 suspend/resume, etc.
620
Davide Pesavento0b2aa132020-12-11 23:00:02 -0500621 The pair ``insert/erase`` is preferred. ``insert/delete`` can also be used if it
622 does not conflict with the ``delete`` keyword of C++.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700623
6242.21. Variable names should not include reference to variable type (do not use Hungarian
625notation).
626
627 .. code-block:: c++
628
629 Line* line; // NOT: Line* pLine;
630 // NOT: Line* linePtr;
631
632 size_t nPoints; // NOT lnPoints
633
634 char* name; // NOT szName
635
6362.22. Negated boolean variable names should be avoided.
637
638 .. code-block:: c++
639
640 bool isError; // NOT: isNoError
641 bool isFound; // NOT: isNotFound
642
6432.23. Enumeration constants recommended to prefix with a common type name.
644
645 .. code-block:: c++
646
647 enum Color {
648 COLOR_RED,
649 COLOR_GREEN,
650 COLOR_BLUE
651 };
652
6532.24. Exceptions can be suffixed with either ``Exception`` (e.g., ``SecurityException``) or
654``Error`` (e.g., ``SecurityError``).
655
Davide Pesavento923ba442019-02-12 22:00:38 -0500656 The recommended method is to declare an exception class ``Exception`` or ``Error`` as
657 a nested type inside the class from which the exception is thrown. For example, when
658 defining a class ``Foo`` that can throw errors, one can write the following:
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700659
660 .. code-block:: c++
661
662 #include <stdexcept>
663
664 class Foo
665 {
Junxiao Shi68b53852018-07-25 13:56:38 -0600666 public:
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700667 class Error : public std::runtime_error
668 {
669 public:
Junxiao Shi68b53852018-07-25 13:56:38 -0600670 // You can inherit constructors from std::runtime_error like this:
671 using std::runtime_error::runtime_error;
672
Davide Pesavento923ba442019-02-12 22:00:38 -0500673 // Additional constructors, if desired, can be declared as usual:
Junxiao Shi68b53852018-07-25 13:56:38 -0600674 Error(const std::string& what, const std::exception& inner)
675 : std::runtime_error(what + ": " + inner.what())
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700676 {
677 }
678 };
679 };
680
681 In addition to that, if class Foo is a base class or interface for some class
682 hierarchy, then child classes should should define their own ``Error`` or
683 ``Exception`` classes that are inherited from the parent's Error class.
684
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07006852.25. Functions (methods returning something) should be named after what they return and
686procedures (void methods) after what they do.
687
688 Increase readability. Makes it clear what the unit should do and especially all the
689 things it is not supposed to do. This again makes it easier to keep the code clean of
690 side effects.
691
6923. Miscellaneous
693----------------
694
6953.1. Exceptions can be used in the code, but should be used only in exceptional cases and
696not in the primary processing path.
697
6983.2. Header files must contain an include guard.
699
Davide Pesavento7e780642018-11-24 15:51:34 -0500700 For example, a header file named ``module/class-name.hpp`` or
701 ``src/module/class-name.hpp`` should have a header guard in the following form:
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700702
703 .. code-block:: c++
704
705 #ifndef APP_MODULE_CLASS_NAME_HPP
706 #define APP_MODULE_CLASS_NAME_HPP
707 ...
708 #endif // APP_MODULE_CLASS_NAME_HPP
709
Davide Pesavento7e780642018-11-24 15:51:34 -0500710 The macro name should reflect the path of the header file relative to the root of the
711 source tree, in order to prevent naming conflicts. The header guard should be prefixed
712 with the application/library name to avoid conflicts with other packages and libraries.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700713
Davide Pesavento7e780642018-11-24 15:51:34 -05007143.3. Include directives for system headers and other external libraries should use
715``<angle brackets>``. Header files in the same source code repository should be included
716using ``"quotes"``.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700717
718 .. code-block:: c++
719
Davide Pesavento7e780642018-11-24 15:51:34 -0500720 #include "ndn-cxx/util/random.hpp"
721
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700722 #include <string>
723 #include <boost/lexical_cast.hpp>
724
Davide Pesavento7e780642018-11-24 15:51:34 -0500725 All of a project's header files should be included with their path relative to
726 the project's source directory. The use of UNIX directory shortcuts ``.``
727 (the current directory) and ``..`` (the parent directory) is discouraged.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700728
Junxiao Shi4f92d872017-07-25 22:04:48 +00007293.4. Include statements should be grouped. Same-project headers should be included first.
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500730Leave an empty line between groups of include statements. Sort alphabetically within a group.
Davide Pesavento7e780642018-11-24 15:51:34 -0500731For example, the include section of ``ndn-cxx/foo/bar.cpp`` may look like this:
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700732
733 .. code-block:: c++
734
Junxiao Shi24c5a002018-12-12 04:47:15 +0000735 #include "ndn-cxx/impl/pending-interest.hpp"
Davide Pesavento7e780642018-11-24 15:51:34 -0500736 #include "ndn-cxx/util/random.hpp"
Junxiao Shi4f92d872017-07-25 22:04:48 +0000737
Davide Pesavento7e780642018-11-24 15:51:34 -0500738 #include <cstdlib>
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700739 #include <fstream>
740 #include <iomanip>
741
742 #include <boost/lexical_cast.hpp>
743 #include <boost/regex.hpp>
744
Davide Pesavento0b2aa132020-12-11 23:00:02 -05007453.5. Definitions that are local to only one ``.cpp`` file should be declared inside that
746file and be placed in an unnamed namespace or declared ``static``.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700747
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07007483.6. Implicit conversion is generally allowed.
749
750 Implicit conversion between integer and floating point numbers can cause problems and
751 should be avoided.
752
Davide Pesavento0b2aa132020-12-11 23:00:02 -0500753 Implicit conversion in constructors that can be called with a single argument is usually
754 undesirable. Therefore, all single-argument constructors should be marked ``explicit``,
755 unless implicit conversion is desirable. In that case, a comment should document the
756 reason for this.
757 As an exception, copy and move constructors should not be explicit, since they do not
758 perform type conversion.
759 Constructors that cannot be called with a single argument may omit ``explicit``.
760 Constructors that take a single ``std::initializer_list`` parameter should also omit
761 ``explicit``, in order to support copy-initialization.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700762
Davide Pesavento0b2aa132020-12-11 23:00:02 -0500763 Avoid C-style casts.
764 Use ``static_cast``, ``dynamic_cast``, ``const_cast``, ``reinterpret_cast``, or
765 ``bit_cast`` instead where appropriate.
766 Use ``static_pointer_cast``, ``dynamic_pointer_cast``, or ``const_pointer_cast``
767 when dealing with ``shared_ptr``.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700768
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07007693.7. Variables should be initialized where they are declared.
770
771 This ensures that variables are valid at any time. Sometimes it is impossible to
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500772 initialize a variable to a valid value where it is declared.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700773
774 .. code-block:: c++
775
776 int x, y, z;
777 getCenter(&x, &y, &z);
778
779 In these cases it should be left uninitialized rather than initialized to some phony
780 value.
781
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -05007823.8. In most cases, class data members should not be declared ``public``.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700783
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500784 Public data members violate the concepts of information hiding and encapsulation.
785 Use private variables and public accessor methods instead.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700786
787 Exceptions to this rule:
788
Davide Pesavento0b2aa132020-12-11 23:00:02 -0500789 * When the class is essentially a passive data structure with no or minimal behavior
790 (equivalent to a C struct, also known as POD type). In this case, all fields should
791 be public and the keyword ``struct`` should be used instead of ``class``.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700792
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500793 * When the class is used only inside the compilation unit, e.g., when implementing pImpl
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700794 idiom (aka Bridge pattern) or similar cases.
795
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07007963.9. C++ pointers and references should have their reference symbol next to the type rather
797than to the name.
798
799 .. code-block:: c++
800
801 float* x; // NOT: float *x;
802 int& y; // NOT: int &y;
803
8043.10. Implicit test for 0 should not be used other than for boolean variables and pointers.
805
806 .. code-block:: c++
807
Davide Pesavento0b2aa132020-12-11 23:00:02 -0500808 if (nLines != 0) // NOT: if (nLines)
809
810 int* ptr = ...
811 if (ptr) // OK
812 if (ptr != nullptr) // also OK
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700813
Davide Pesaventobbca1b92015-12-25 20:06:00 +01008143.11. *(removed)*
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700815
8163.12. Loop variables should be initialized immediately before the loop.
817
818 .. code-block:: c++
819
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500820 bool isDone = false; // NOT: bool isDone = false;
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700821 while (!isDone) { // // other stuff
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500822 ... // while (!isDone) {
823 } // ...
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700824 // }
825
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -05008263.13. The form ``while (true)`` should be used for infinite loops.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700827
828 .. code-block:: c++
829
830 while (true) {
831 ...
832 }
833
834 // NOT:
835 for (;;) { // NO!
Davide Pesavento0b2aa132020-12-11 23:00:02 -0500836 ...
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700837 }
838 while (1) { // NO!
Davide Pesavento0b2aa132020-12-11 23:00:02 -0500839 ...
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700840 }
841
8423.14. Complex conditional expressions must be avoided. Introduce temporary boolean variables
843instead.
844
845 .. code-block:: c++
846
847 bool isFinished = (elementNo < 0) || (elementNo > maxElement);
848 bool isRepeatedEntry = elementNo == lastElement;
849 if (isFinished || isRepeatedEntry) {
850 ...
851 }
852
853 // NOT:
854 // if ((elementNo < 0) || (elementNo > maxElement) || elementNo == lastElement) {
855 // ...
856 // }
857
858 By assigning boolean variables to expressions, the program gets automatic
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500859 documentation. The construction will be easier to read, debug, and maintain.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700860
8613.15. The conditional should be put on a separate line.
862
863 .. code-block:: c++
864
865 if (isDone) // NOT: if (isDone) doCleanup();
866 doCleanup();
867
868 This is for debugging purposes. When writing on a single line, it is not apparent
869 whether the test is really true or not.
870
8713.16. Assignment statements in conditionals must be avoided.
872
873 .. code-block:: c++
874
875 File* fileHandle = open(fileName, "w");
876 if (!fileHandle) {
877 ...
878 }
879
880 // NOT
881 // if (!(fileHandle = open(fileName, "w"))) {
882 // ..
883 // }
884
8853.17. The use of magic numbers in the code should be avoided. Numbers other than 0 and 1
886should be considered declared as named constants instead.
887
888 If the number does not have an obvious meaning by itself, the readability is enhanced
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500889 by introducing a named constant instead. A different approach is to introduce a method
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700890 from which the constant can be accessed.
891
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -05008923.18. Floating point literals should always be written with a decimal point, at least one
893decimal, and without omitting 0 before the decimal point.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700894
895 .. code-block:: c++
896
897 double total = 0.0; // NOT: double total = 0;
898 double someValue = 0.1; // NOT double someValue = .1;
899 double speed = 3.0e8; // NOT: double speed = 3e8;
900 double sum;
901 ...
902 sum = (a + b) * 10.0;
903
9043.19. ``goto`` should not be used.
905
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500906 ``goto`` statements violate the idea of structured code. Only in very few cases (for
907 instance, breaking out of deeply nested structures) should ``goto`` be considered,
908 and only if the alternative structured counterpart is proven to be less readable.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700909
Davide Pesavento28530b62025-05-07 13:22:21 -04009103.20. ``nullptr`` should be used to represent a null pointer, instead of ``0`` or ``NULL``.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700911
9123.21. Logical units within a block should be separated by one blank line.
913
914 .. code-block:: c++
915
916 Matrix4x4 matrix = new Matrix4x4();
917
918 double cosAngle = Math.cos(angle);
919 double sinAngle = Math.sin(angle);
920
921 matrix.setElement(1, 1, cosAngle);
922 matrix.setElement(1, 2, sinAngle);
923 matrix.setElement(2, 1, -sinAngle);
924 matrix.setElement(2, 2, cosAngle);
925
926 multiply(matrix);
927
928 Enhance readability by introducing white space between logical units of a block.
929
9303.22. Variables in declarations can be left aligned.
931
932 .. code-block:: c++
933
934 AsciiFile* file;
935 int nPoints;
936 float x, y;
937
938 Enhance readability. The variables are easier to spot from the types by alignment.
939
9403.23. Use alignment wherever it enhances readability.
941
942 .. code-block:: c++
943
944 value = (potential * oilDensity) / constant1 +
945 (depth * waterDensity) / constant2 +
946 (zCoordinateValue * gasDensity) / constant3;
947
948 minPosition = computeDistance(min, x, y, z);
949 averagePosition = computeDistance(average, x, y, z);
950
951 There are a number of places in the code where white space can be included to enhance
952 readability even if this violates common guidelines. Many of these cases have to do
953 with code alignment. General guidelines on code alignment are difficult to give, but
954 the examples above should give a general clue.
955
9563.24. All comments should be written in English.
957
Davide Pesaventoaf1d6cf2017-11-06 23:53:01 -0500958 In an international environment, English is the preferred language.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700959
Alexander Afanasyevdfa52c42014-04-24 21:10:11 -07009603.25. Use ``//`` for all comments, including multi-line comments.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700961
962 .. code-block:: c++
963
964 // Comment spanning
965 // more than one line.
966
967 Since multilevel C-commenting is not supported, using ``//`` comments ensure that it
968 is always possible to comment out entire sections of a file using ``/* */`` for
969 debugging purposes etc.
970
971 There should be a space between the ``//`` and the actual comment, and comments should
972 always start with an upper case letter and end with a period.
973
974 However, method and class documentation comments should use ``/** */`` style for
Junxiao Shibd2cedb2017-07-05 18:51:52 +0000975 Doxygen, JavaDoc and JSDoc. License boilerplate should use ``/* */`` style.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700976
9773.26. Comments should be included relative to their position in the code.
978
979 .. code-block:: c++
980
981 while (true) {
982 // Do something
983 something();
984 }
985
986 // NOT:
987 while (true) {
988 // Do something
989 something();
990 }
991
992 This is to avoid that the comments break the logical structure of the program.
Junxiao Shiae61aac2014-11-04 14:57:38 -0700993
9943.27. Use ``BOOST_ASSERT`` and ``BOOST_ASSERT_MSG`` for runtime assertions.
995
996 .. code-block:: c++
997
998 int x = 1;
999 int y = 2;
1000 int z = x + y;
1001 BOOST_ASSERT(z - y == x);
1002
Davide Pesavento0b2aa132020-12-11 23:00:02 -05001003 The expression passed to ``BOOST_ASSERT`` must not have side effects,
1004 because it may not be evaluated in release builds.
Junxiao Shiae61aac2014-11-04 14:57:38 -07001005
Davide Pesavento0b2aa132020-12-11 23:00:02 -050010063.28. Use ``static_assert`` for compile-time assertions.
Junxiao Shiae61aac2014-11-04 14:57:38 -07001007
Junxiao Shiae61aac2014-11-04 14:57:38 -07001008 .. code-block:: c++
1009
1010 class BaseClass
1011 {
1012 };
1013
1014 class DerivedClass : public BaseClass
1015 {
1016 };
1017
1018 static_assert(std::is_base_of<BaseClass, DerivedClass>::value,
1019 "DerivedClass must inherit from BaseClass");
Junxiao Shic0a8c3b2014-11-08 12:09:05 -07001020
Davide Pesavento0b2aa132020-12-11 23:00:02 -050010213.29. The ``auto`` type specifier may be used for local variables if a human reader can
1022easily deduce the actual type, or if it makes the code safer.
Junxiao Shic0a8c3b2014-11-08 12:09:05 -07001023
1024 .. code-block:: c++
1025
1026 std::vector<int> intVector;
Davide Pesavento0b2aa132020-12-11 23:00:02 -05001027 auto i = intVector.find(4); // OK
Junxiao Shic0a8c3b2014-11-08 12:09:05 -07001028
Davide Pesavento0b2aa132020-12-11 23:00:02 -05001029 auto stringSet = std::make_shared<std::set<std::string>>(); // OK
Junxiao Shic0a8c3b2014-11-08 12:09:05 -07001030
Davide Pesavento0b2aa132020-12-11 23:00:02 -05001031 std::vector<std::string> strings;
1032 for (const auto& str : strings) { // OK, iterating over the elements of a container
1033 std::cout << str;
Junxiao Shic0a8c3b2014-11-08 12:09:05 -07001034 }
Davide Pesavento0b2aa132020-12-11 23:00:02 -05001035
1036 obj.onEvent([] (auto&&...) { std::cout << "hi!"; }); // OK, unused lambda parameters
1037
1038 auto x = foo(); // BAD unless foo() is declared nearby or has a well-known prototype
Junxiao Shia76bbc92015-03-23 11:05:37 -07001039
Davide Pesaventode2a1c22016-12-11 15:46:13 -050010403.30. Use the ``override`` or ``final`` specifier when overriding a virtual
1041member function or a virtual destructor.
Junxiao Shia76bbc92015-03-23 11:05:37 -07001042
Davide Pesavento0b2aa132020-12-11 23:00:02 -05001043 ``virtual`` must not be used along with ``final`` so that the compiler can generate
1044 an error when a final function does not override.
Davide Pesaventode2a1c22016-12-11 15:46:13 -05001045
Davide Pesavento0b2aa132020-12-11 23:00:02 -05001046 ``virtual`` should not be used along with ``override`` for consistency with ``final``.
Junxiao Shia76bbc92015-03-23 11:05:37 -07001047
1048 .. code-block:: c++
1049
1050 class Stream
1051 {
1052 public:
1053 virtual void
1054 open();
1055 };
1056
1057 class InputStream : public Stream
1058 {
1059 public:
Davide Pesaventode2a1c22016-12-11 15:46:13 -05001060 void
Junxiao Shia76bbc92015-03-23 11:05:37 -07001061 open() override;
1062 };
1063
1064 class Console : public InputStream
1065 {
1066 public:
Davide Pesaventode2a1c22016-12-11 15:46:13 -05001067 void
1068 open() final;
Junxiao Shia76bbc92015-03-23 11:05:37 -07001069 };
1070
Spyridon Mastorakis0d2ed2e2015-07-27 19:09:12 -070010713.31. The recommended way to throw an exception derived from ``std::exception`` is to use
Davide Pesavento923ba442019-02-12 22:00:38 -05001072``NDN_THROW`` or one of the other ``NDN_THROW_*`` macros.
Davide Pesavento0b2aa132020-12-11 23:00:02 -05001073
1074 Exceptions thrown using these macros will be augmented with additional diagnostic
1075 information, including the file name, line number, and function name from which
1076 the exception was thrown.
1077
1078 The extended diagnostic information contained in the exception can be printed with
1079 ``boost::diagnostic_information()``.
1080
1081 .. code-block:: c++
1082
1083 #include <boost/exception/diagnostic_information.hpp>
1084 #include <iostream>
1085
1086 try {
1087 operationThatMayThrow();
1088 }
1089 catch (const std::exception& e) {
1090 std::cerr << boost::diagnostic_information(e);
1091 }