blob: 354038e1ce6db1713e1f1340af0c5af8df10f174 [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
55 Note that code inside namespace is **not** indented. Avoid following:
56
57 .. code-block:: c++
58
59 // NOT
60 //
61 // namespace example {
62 //
63 // code;
64 // moreCode;
65 //
66 // } // namespace example
67
681.4. The class declarations should have the following form:
69
70 .. code-block:: c++
71
72 class SomeClass : public BaseClass
73 {
74 public:
75 ... <public methods> ...
76 protected:
77 ... <protected methods> ...
78 private:
79 ... <private methods> ...
80
81 public:
82 ... <public data> ...
83 protected:
84 ... <protected data> ...
85 private:
86 ... <private data> ...
87 };
88
89 ``public``, ``protected``, ``private`` may be repeated several times without
90 interleaving (e.g., public, public, public, private, private) if this allows better
91 readability of the code.
92
93 Nested classes can be defined in appropriate visibility section, either in methods
94 block, data block, or in a separate section (depending which one provides better code
95 readability).
96
971.5. Method and function definitions should have the following form:
98
99 .. code-block:: c++
100
101 void
102 someMethod()
103 {
104 ...
105 }
106
107 void
108 SomeClass::someMethod()
109 {
110 ...
111 }
112
1131.6. The ``if-else`` class of statements should have the following form:
114
115 .. code-block:: c++
116
117 if (condition) {
118 statements;
119 }
120
121 if (condition) {
122 statements;
123 }
124 else {
125 statements;
126 }
127
128 if (condition) {
129 statements;
130 }
131 else if (condition) {
132 statements;
133 }
134 else {
135 statements;
136 }
137
138 or (less preferred):
139
140 .. code-block:: c++
141
142 if (condition)
143 {
144 statements;
145 }
146 else if (condition)
147 {
148 statements;
149 }
150 else
151 {
152 statements;
153 }
154
1551.7. A ``for`` statement should have the following form:
156
157 .. code-block:: c++
158
159 for (initialization; condition; update) {
160 statements;
161 }
162
163 or (less preferred):
164
165 .. code-block:: c++
166
167 for (initialization; condition; update)
168 {
169 statements;
170 }
171
172 An empty for statement should have the following form:
173
174 .. code-block:: c++
175
176 for (initialization; condition; update)
177 ;
178
179 This emphasizes the fact that the for statement is empty and it makes it obvious for
180 the reader that this is intentional. Empty loops should be avoided however.
181
1821.8. A ``while`` statement should have the following form:
183
184 .. code-block:: c++
185
186 while (condition) {
187 statements;
188 }
189
190 or (less preferred):
191
192 .. code-block:: c++
193
194 while (condition)
195 {
196 statements;
197 }
198
1991.9. A ``do-while`` statement should have the following form:
200
201 .. code-block:: c++
202
203 do {
204 statements;
205 } while (condition);
206
2071.10. A ``switch`` statement should have the following form:
208
209 .. code-block:: c++
210
211 switch (condition) {
Wentao Shang3aa4f412015-08-18 21:12:50 -0700212 case ABC: // 2 space indent
213 statements; // 4 space indent
Davide Pesavento1c597a12017-10-06 15:34:24 -0400214 NDN_CXX_FALLTHROUGH;
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700215
Wentao Shang3aa4f412015-08-18 21:12:50 -0700216 case DEF:
217 statements;
218 break;
219
220 case XYZ: {
221 statements;
222 break;
223 }
224
225 default:
226 statements;
227 break;
228 }
229
230 When curly braces are used inside a ``case`` block, the braces must cover the entire
231 ``case`` block.
232
233 .. code-block:: c++
234
235 switch (condition) {
236 // Correct style
237 case A0: {
238 statements;
239 break;
240 }
241
242 // Correct style
243 case A1: {
244 statements;
Davide Pesavento1c597a12017-10-06 15:34:24 -0400245 NDN_CXX_FALLTHROUGH;
Wentao Shang3aa4f412015-08-18 21:12:50 -0700246 }
247
248 // Incorrect style: braces should cover the entire case block
249 case B: {
250 statements;
251 }
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700252 statements;
253 break;
254
Wentao Shang3aa4f412015-08-18 21:12:50 -0700255 default:
256 break;
257 }
258
259 The following style is still allowed when none of the ``case`` blocks has curly braces.
260
261 .. code-block:: c++
262
263 switch (condition) {
264 case ABC: // no indent
265 statements; // 2 space indent
Davide Pesavento1c597a12017-10-06 15:34:24 -0400266 NDN_CXX_FALLTHROUGH;
Wentao Shang3aa4f412015-08-18 21:12:50 -0700267
268 case DEF:
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700269 statements;
270 break;
271
272 default:
273 statements;
274 break;
275 }
276
Davide Pesavento1c597a12017-10-06 15:34:24 -0400277 The ``NDN_CXX_FALLTHROUGH;`` annotation must be included whenever there is
278 a case without a break statement. Leaving the break out is a common error,
279 and it must be made clear that it is intentional when it is not there.
280 Moreover, modern compilers will warn when a case that falls through is not
281 explicitly annotated.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700282
2831.11. A ``try-catch`` statement should have the following form:
284
285 .. code-block:: c++
286
287 try {
288 statements;
289 }
Davide Pesaventocd183d22015-09-23 16:40:28 +0200290 catch (const Exception& exception) {
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700291 statements;
292 }
293
294 or (less preferred):
295
296 .. code-block:: c++
297
298 try
299 {
300 statements;
301 }
Davide Pesaventocd183d22015-09-23 16:40:28 +0200302 catch (const Exception& exception)
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700303 {
304 statements;
305 }
306
3071.12. The incompleteness of split lines must be made obvious.
308
309 .. code-block:: c++
310
311 totalSum = a + b + c +
312 d + e;
313 function(param1, param2,
314 param3);
315 for (int tableNo = 0; tableNo < nTables;
316 tableNo += tableStep) {
317 ...
318 }
319
320 Split lines occurs when a statement exceed the 80 column limit given above. It is
321 difficult to give rigid rules for how lines should be split, but the examples above should
322 give a general hint.In general:
323
324 * Break after a comma.
325 * Break after an operator.
326 * Align the new line with the beginning of the expression on the previous line.
327
328 Exceptions:
329
330 * The following is the standard practice with operator<<:
331
332 .. code-block:: c++
333
334 std::cout << "Something here "
335 << "Something there" << std::endl;
336
3371.13. When class variables need to be initialized in the constructor, the initialization
338should take the following form:
339
340 .. code-block:: c++
341
342 SomeClass::SomeClass(int value, const std::string& string)
343 : m_value(value)
344 , m_string(string)
345 ...
346 {
347 }
348
349 Each initialization should be put on a separate line, starting either with the colon
350 for the first initialization or with comma for all subsequent initializations.
351
Junxiao Shi45c13842014-11-02 15:36:04 -07003521.14. A range-based ``for`` statement should have the following form:
353
354 .. code-block:: c++
355
356 for (T i : range) {
357 statements;
358 }
359
Junxiao Shicf698182014-11-03 08:37:42 -07003601.15. A lambda expression should have the following form:
361
362 .. code-block:: c++
363
364 [&capture1, capture2] (T1 arg1, T2 arg2) {
365 statements;
366 }
367
368 [&capture1, capture2] (T1 arg1, T2 arg2) mutable {
369 statements;
370 }
371
372 [this] (T arg) {
373 statements;
374 }
375
376 If the function has no parameters, ``()`` should be omitted.
377
378 .. code-block:: c++
379
380 [&capture1, capture2] {
381 statements;
382 }
383
384 Capture-all (``[&]`` and ``[=]``) is permitted, but its usage should be minimized.
385 Only use capture-all when it significantly simplifies code and improves readability.
386
387 .. code-block:: c++
388
389 [&] (T arg) {
390 statements;
391 }
392
393 [=] (T arg) {
394 statements;
395 }
396
397 Trailing return type should be omitted. Write them only when compiler cannot deduce
398 return type automatically, or when it improves readability.
399 ``()`` is required by C++ standard when trailing return type is written.
400
401 .. code-block:: c++
402
403 [] (T arg) -> int {
404 statements;
405 }
406
407 [] () -> int {
408 statements;
409 }
410
411 If the function body has only one line, and the whole lambda expression can fit in one line,
412 the following form is also acceptable:
413
414 .. code-block:: c++
415
416 [&capture1, capture2] (T1 arg1, T2 arg2) { statement; }
417
418 No-op can be written in a more compact form:
419
420 .. code-block:: c++
421
422 []{}
423
Junxiao Shi8b12a5a2014-11-25 10:42:47 -07004241.16. List initialization should have the following form:
425
426 .. code-block:: c++
427
428 T object{arg1, arg2};
429
430 T{arg1, arg2};
431
432 new T{arg1, arg2};
433
434 return {arg1, arg2};
435
436 function({arg1, arg2}, otherArgument);
437
438 object[{arg1, arg2}];
439
440 T({arg1, arg2})
441
442 class Class
443 {
444 private:
Davide Pesaventoe6e6fde2016-04-16 14:44:45 +0200445 T m_member = {arg1, arg2};
Junxiao Shi8b12a5a2014-11-25 10:42:47 -0700446 static T s_member = {arg1, arg2};
447 };
448
449 Class::Class()
450 : m_member{arg1, arg2}
451 {
452 }
453
454 T object = {arg1, arg2};
455
456 An empty braced-init-list is written as ``{}``. For example:
457
458 .. code-block:: c++
459
460 T object{};
461
462 T object = {};
463
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07004642. Naming Conventions
465---------------------
466
4672.1. C++ header files should have the extension ``.hpp``. Source files should have the
468extension ``.cpp``
469
470 File names should be all lower case. If the class name
471 is a composite of several words, each word in a file name should be separated with a
472 dash (-). A class should be declared in a header file and defined in a source file
473 where the name of the files match the name of the class.
474
475 ::
476
477 my-class.hpp, my-class.cpp
478
479
4802.2. Names representing types must be written in English in mixed case starting with upper case.
481
482 .. code-block:: c++
483
484 class MyClass;
485 class Line;
486 class SavingsAccount;
487
4882.3. Variable names must be written in English in mixed case starting with lower case.
489
490 .. code-block:: c++
491
492 MyClass myClass;
493 Line line;
494 SavingsAccount savingsAccount;
495 int theAnswerToLifeTheUniverseAndEverything;
496
4972.4. Named constants (including enumeration values) must be all uppercase using underscore
498to separate words.
499
500 .. code-block:: c++
501
502 const int MAX_ITERATIONS = 25;
503 const std::string COLOR_RED = "red";
504 static const double PI = 3.14;
505
506 In some cases, it is a better (or is the only way for complex constants in header-only
507 classes) to implement the value as a method:
508
509 .. code-block:: c++
510
511 int
512 getMaxIterations()
513 {
514 return 25;
515 }
516
5172.5. Names representing methods or functions must be commands starting with a verb and
518written in mixed case starting with lower case.
519
520 .. code-block:: c++
521
522 std::string
523 getName()
524 {
525 ...
526 }
527
528 double
529 computeTotalWidth()
530 {
531 ...
532 }
533
5342.6. Names representing namespaces should be all lowercase.
535
536 .. code-block:: c++
537
538 namespace model {
539 namespace analyzer {
540
541 ...
542
543 } // namespace analyzer
544 } // namespace model
545
5462.7. Names representing generic template types should be a single uppercase letter
547
548 .. code-block:: c++
549
550 template<class T> ...
551 template<class C, class D> ...
552
553 However, when template parameter represents a certain concept and expected to have a
554 certain interface, the name should be explicitly spelled out:
555
556 .. code-block:: c++
557
558 template<class FaceBase> ...
559 template<class Packet> ...
560
5612.8. Abbreviations and acronyms must not be uppercase when used as name.
562
563 .. code-block:: c++
564
565 exportHtmlSource(); // NOT: exportHTMLSource();
566 openDvdPlayer(); // NOT: openDVDPlayer();
567
5682.9. Global variables should have ``g_`` prefix
569
570 .. code-block:: c++
571
572 g_mainWindow.open();
573 g_applicationContext.getName();
574
575 In general, the use of global variables should be avoided. Consider using singleton
576 objects instead.
577
5782.10. Private class variables should have ``m_`` prefix. Static class variables should have
579``s_`` prefix.
580
581 .. code-block:: c++
582
583 class SomeClass
584 {
585 private:
586 int m_length;
587
588 static std::string s_name;
589 };
590
591
5922.11. Variables with a large scope should have long (explicit) names, variables with a small
593scope can have short names.
594
595 Scratch variables used for temporary storage or indices are best kept short. A
596 programmer reading such variables should be able to assume that its value is not used
597 outside of a few lines of code. Common scratch variables for integers are ``i``,
598 ``j``, ``k``, ``m``, ``n`` and for characters ``c`` and ``d``.
599
6002.12. The name of the object is implicit, and should be avoided in a method name.
601
602 .. code-block:: c++
603
604 line.getLength(); // NOT: line.getLineLength();
605
606 The latter seems natural in the class declaration, but proves superfluous in use, as
607 shown in the example.
608
6092.13. The terms ``get/set`` must be used where an attribute is accessed directly.
610
611 .. code-block:: c++
612
613 employee.getName();
614 employee.setName(name);
615
616 matrix.getElement(2, 4);
617 matrix.setElement(2, 4, value);
618
6192.14. The term ``compute`` can be used in methods where something is computed.
620
621 .. code-block:: c++
622
623 valueSet.computeAverage();
624 matrix.computeInverse()
625
626 Give the reader the immediate clue that this is a potentially time-consuming operation,
627 and if used repeatedly, he might consider caching the result. Consistent use of the term
628 enhances readability.
629
6302.15. The term ``find`` can be used in methods where something is looked up.
631
632 .. code-block:: c++
633
634 vertex.findNearestVertex();
635 matrix.findMinElement();
636
637 Give the reader the immediate clue that this is a simple look up method with a minimum
638 of computations involved. Consistent use of the term enhances readability.
639
6402.16. Plural form should be used on names representing a collection of objects.
641
642 .. code-block:: c++
643
644 vector<Point> points;
645 int values[];
646
647 Enhances readability since the name gives the user an immediate clue of the type of
648 the variable and the operations that can be performed on its elements.
649
6502.17. The prefix ``n`` should be used for variables representing a number of objects.
651
652 .. code-block:: c++
653
654 nPoints, nLines
655
656 The notation is taken from mathematics where it is an established convention for
657 indicating a number of objects.
658
659
6602.18. The suffix ``No`` should be used for variables representing an entity number.
661
662 .. code-block:: c++
663
664 tableNo, employeeNo
665
666 The notation is taken from mathematics where it is an established convention for
667 indicating an entity number. An elegant alternative is to prefix such variables with
668 an ``i``: ``iTable``, ``iEmployee``. This effectively makes them named iterators.
669
6702.19. The prefix ``is``, ``has``, ``need``, or similar should be used for boolean variables and
671methods.
672
673 .. code-block:: c++
674
675 isSet, isVisible, isFinished, isFound, isOpen
676 needToConvert, needToFinish
677
6782.20. Complement names must be used for complement operations, reducing complexity by
679symmetry.
680
681 ::
682
683 get/set, add/remove, create/destroy, start/stop, insert/delete,
684 increment/decrement, old/new, begin/end, first/last, up/down, min/max,
685 next/previous (and commonly used next/prev), open/close, show/hide,
686 suspend/resume, etc.
687
688 Pair ``insert/erase`` should be preferred. ``insert/delete`` can also be used if it
689 does not conflict with C++ delete keyword.
690
6912.21. Variable names should not include reference to variable type (do not use Hungarian
692notation).
693
694 .. code-block:: c++
695
696 Line* line; // NOT: Line* pLine;
697 // NOT: Line* linePtr;
698
699 size_t nPoints; // NOT lnPoints
700
701 char* name; // NOT szName
702
7032.22. Negated boolean variable names should be avoided.
704
705 .. code-block:: c++
706
707 bool isError; // NOT: isNoError
708 bool isFound; // NOT: isNotFound
709
7102.23. Enumeration constants recommended to prefix with a common type name.
711
712 .. code-block:: c++
713
714 enum Color {
715 COLOR_RED,
716 COLOR_GREEN,
717 COLOR_BLUE
718 };
719
7202.24. Exceptions can be suffixed with either ``Exception`` (e.g., ``SecurityException``) or
721``Error`` (e.g., ``SecurityError``).
722
723 The recommended method is to declare exception class ``Exception`` or ``Error`` as an
724 inner class, from which the exception is thrown. For example, when declaring class
725 ``Foo`` that can throw errors, one can write the following:
726
727 .. code-block:: c++
728
729 #include <stdexcept>
730
731 class Foo
732 {
733 class Error : public std::runtime_error
734 {
735 public:
736 explicit
737 Error(const std::string& what)
738 : std::runtime_error(what)
739 {
740 }
741 };
742 };
743
744 In addition to that, if class Foo is a base class or interface for some class
745 hierarchy, then child classes should should define their own ``Error`` or
746 ``Exception`` classes that are inherited from the parent's Error class.
747
748
7492.25. Functions (methods returning something) should be named after what they return and
750procedures (void methods) after what they do.
751
752 Increase readability. Makes it clear what the unit should do and especially all the
753 things it is not supposed to do. This again makes it easier to keep the code clean of
754 side effects.
755
7563. Miscellaneous
757----------------
758
7593.1. Exceptions can be used in the code, but should be used only in exceptional cases and
760not in the primary processing path.
761
7623.2. Header files must contain an include guard.
763
764 For example, header file located in ``module/class-name.hpp`` or in
765 ``src/module/class-name.hpp`` should have header guard in the following form:
766
767 .. code-block:: c++
768
769 #ifndef APP_MODULE_CLASS_NAME_HPP
770 #define APP_MODULE_CLASS_NAME_HPP
771 ...
772 #endif // APP_MODULE_CLASS_NAME_HPP
773
774 The name should follow the location of the file inside the source tree and prevents
775 naming conflicts. Header guard should be prefixed with the application/library name
776 to avoid conflicts with other packaged and libraries.
777
7783.3. Header files which are in the same source distribution should be included in
779``"quotes"``, if possible with a path relative to the source file. Header files for
780system and other external libraries should be included in ``<angle brackets>``.
781
782 .. code-block:: c++
783
784 #include <string>
785 #include <boost/lexical_cast.hpp>
786
787 #include "util/random.hpp"
788
Junxiao Shi4f92d872017-07-25 22:04:48 +00007893.4. Include statements should be grouped. Same-project headers should be included first.
790Leave an empty line between groups of include statements. Sorted alphabetically within a group.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700791
792 .. code-block:: c++
793
Junxiao Shi4f92d872017-07-25 22:04:48 +0000794 #include "detail/pending-interest.hpp"
795 #include "util/random.hpp"
796
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700797 #include <fstream>
798 #include <iomanip>
799
800 #include <boost/lexical_cast.hpp>
801 #include <boost/regex.hpp>
802
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700803
8043.5. Types that are local to one file only can be declared inside that file.
805
806
8073.6. Implicit conversion is generally allowed.
808
809 Implicit conversion between integer and floating point numbers can cause problems and
810 should be avoided.
811
812 Implicit conversion in single-argument constructor is usually undesirable. Therefore, all
813 single-argument constructors should be marked 'explicit', unless implicit conversion is
814 desirable. In that case, a comment should document the reason.
815
816 Avoid C-style casts. Use ``static_cast``, ``dynamic_cast``, ``reinterpret_cast``,
817 ``const_cast`` instead where appropriate. Use ``static_pointer_cast``,
818 ``dynamic_pointer_cast``, ``const_pointer_cast`` when dealing with ``shared_ptr``.
819
820
8213.7. Variables should be initialized where they are declared.
822
823 This ensures that variables are valid at any time. Sometimes it is impossible to
824 initialize a variable to a valid value where it is declared:
825
826 .. code-block:: c++
827
828 int x, y, z;
829 getCenter(&x, &y, &z);
830
831 In these cases it should be left uninitialized rather than initialized to some phony
832 value.
833
8343.8. In most cases, class instance variables should not be declared public.
835
836 The concepts of information hiding and encapsulation are violated by public variables. Use
837 private variables and access methods instead.
838
839 Exceptions to this rule:
840
841 * when the class is essentially a dumb data structure with no or minimal behavior
842 (equivalent to a C struct, also known as PODS). In this case it is appropriate to make
843 the instance variables public by using struct.
844
845 * when the class is used only inside the compilation unit, e.g., when implementing pImpl
846 idiom (aka Bridge pattern) or similar cases.
847
848
8493.9. C++ pointers and references should have their reference symbol next to the type rather
850than to the name.
851
852 .. code-block:: c++
853
854 float* x; // NOT: float *x;
855 int& y; // NOT: int &y;
856
8573.10. Implicit test for 0 should not be used other than for boolean variables and pointers.
858
859 .. code-block:: c++
860
861 if (nLines != 0) // NOT: if (nLines)
862 if (value != 0.0) // NOT: if (value)
863
Davide Pesaventobbca1b92015-12-25 20:06:00 +01008643.11. *(removed)*
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700865
8663.12. Loop variables should be initialized immediately before the loop.
867
868 .. code-block:: c++
869
870 isDone = false; // NOT: bool isDone = false;
871 while (!isDone) { // // other stuff
872 : // while (!isDone) {
873 } // :
874 // }
875
8763.13. The form while (true) should be used for infinite loops.
877
878 .. code-block:: c++
879
880 while (true) {
881 ...
882 }
883
884 // NOT:
885 for (;;) { // NO!
886 :
887 }
888 while (1) { // NO!
889 :
890 }
891
8923.14. Complex conditional expressions must be avoided. Introduce temporary boolean variables
893instead.
894
895 .. code-block:: c++
896
897 bool isFinished = (elementNo < 0) || (elementNo > maxElement);
898 bool isRepeatedEntry = elementNo == lastElement;
899 if (isFinished || isRepeatedEntry) {
900 ...
901 }
902
903 // NOT:
904 // if ((elementNo < 0) || (elementNo > maxElement) || elementNo == lastElement) {
905 // ...
906 // }
907
908 By assigning boolean variables to expressions, the program gets automatic
909 documentation. The construction will be easier to read, debug and maintain.
910
9113.15. The conditional should be put on a separate line.
912
913 .. code-block:: c++
914
915 if (isDone) // NOT: if (isDone) doCleanup();
916 doCleanup();
917
918 This is for debugging purposes. When writing on a single line, it is not apparent
919 whether the test is really true or not.
920
9213.16. Assignment statements in conditionals must be avoided.
922
923 .. code-block:: c++
924
925 File* fileHandle = open(fileName, "w");
926 if (!fileHandle) {
927 ...
928 }
929
930 // NOT
931 // if (!(fileHandle = open(fileName, "w"))) {
932 // ..
933 // }
934
9353.17. The use of magic numbers in the code should be avoided. Numbers other than 0 and 1
936should be considered declared as named constants instead.
937
938 If the number does not have an obvious meaning by itself, the readability is enhanced
939 by introducing a named constant instead. A different approach is to introduce a method
940 from which the constant can be accessed.
941
9423.18. Floating point constants should always be written with decimal point, at least one
943 decimal, and without omitting 0 before decimal point.
944
945 .. code-block:: c++
946
947 double total = 0.0; // NOT: double total = 0;
948 double someValue = 0.1; // NOT double someValue = .1;
949 double speed = 3.0e8; // NOT: double speed = 3e8;
950 double sum;
951 ...
952 sum = (a + b) * 10.0;
953
9543.19. ``goto`` should not be used.
955
956Goto statements violate the idea of structured code. Only in some very few cases (for
957instance breaking out of deeply nested structures) should goto be considered, and only if
958the alternative structured counterpart is proven to be less readable.
959
Junxiao Shi03b15b32014-10-30 21:10:25 -07009603.20. ``nullptr`` should be used to represent a null pointer, instead of "0" or "NULL".
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -0700961
9623.21. Logical units within a block should be separated by one blank line.
963
964 .. code-block:: c++
965
966 Matrix4x4 matrix = new Matrix4x4();
967
968 double cosAngle = Math.cos(angle);
969 double sinAngle = Math.sin(angle);
970
971 matrix.setElement(1, 1, cosAngle);
972 matrix.setElement(1, 2, sinAngle);
973 matrix.setElement(2, 1, -sinAngle);
974 matrix.setElement(2, 2, cosAngle);
975
976 multiply(matrix);
977
978 Enhance readability by introducing white space between logical units of a block.
979
9803.22. Variables in declarations can be left aligned.
981
982 .. code-block:: c++
983
984 AsciiFile* file;
985 int nPoints;
986 float x, y;
987
988 Enhance readability. The variables are easier to spot from the types by alignment.
989
9903.23. Use alignment wherever it enhances readability.
991
992 .. code-block:: c++
993
994 value = (potential * oilDensity) / constant1 +
995 (depth * waterDensity) / constant2 +
996 (zCoordinateValue * gasDensity) / constant3;
997
998 minPosition = computeDistance(min, x, y, z);
999 averagePosition = computeDistance(average, x, y, z);
1000
1001 There are a number of places in the code where white space can be included to enhance
1002 readability even if this violates common guidelines. Many of these cases have to do
1003 with code alignment. General guidelines on code alignment are difficult to give, but
1004 the examples above should give a general clue.
1005
10063.24. All comments should be written in English.
1007
1008 In an international environment English is the preferred language.
1009
Alexander Afanasyevdfa52c42014-04-24 21:10:11 -070010103.25. Use ``//`` for all comments, including multi-line comments.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07001011
1012 .. code-block:: c++
1013
1014 // Comment spanning
1015 // more than one line.
1016
1017 Since multilevel C-commenting is not supported, using ``//`` comments ensure that it
1018 is always possible to comment out entire sections of a file using ``/* */`` for
1019 debugging purposes etc.
1020
1021 There should be a space between the ``//`` and the actual comment, and comments should
1022 always start with an upper case letter and end with a period.
1023
1024 However, method and class documentation comments should use ``/** */`` style for
Junxiao Shibd2cedb2017-07-05 18:51:52 +00001025 Doxygen, JavaDoc and JSDoc. License boilerplate should use ``/* */`` style.
Alexander Afanasyev3aeeaeb2014-04-22 23:34:23 -07001026
10273.26. Comments should be included relative to their position in the code.
1028
1029 .. code-block:: c++
1030
1031 while (true) {
1032 // Do something
1033 something();
1034 }
1035
1036 // NOT:
1037 while (true) {
1038 // Do something
1039 something();
1040 }
1041
1042 This is to avoid that the comments break the logical structure of the program.
Junxiao Shiae61aac2014-11-04 14:57:38 -07001043
10443.27. Use ``BOOST_ASSERT`` and ``BOOST_ASSERT_MSG`` for runtime assertions.
1045
1046 .. code-block:: c++
1047
1048 int x = 1;
1049 int y = 2;
1050 int z = x + y;
1051 BOOST_ASSERT(z - y == x);
1052
1053 The expression passed to ``BOOST_ASSERT`` MUST NOT have side effects,
1054 because it MAY NOT be evaluated in release builds.
1055
10563.28. Use ``static_assert`` for static assertions.
1057
Junxiao Shiae61aac2014-11-04 14:57:38 -07001058 .. code-block:: c++
1059
1060 class BaseClass
1061 {
1062 };
1063
1064 class DerivedClass : public BaseClass
1065 {
1066 };
1067
1068 static_assert(std::is_base_of<BaseClass, DerivedClass>::value,
1069 "DerivedClass must inherit from BaseClass");
Junxiao Shic0a8c3b2014-11-08 12:09:05 -07001070
10713.29. ``auto`` type specifier MAY be used for local variables, if a human reader
1072 can easily deduce the actual type.
1073
1074 .. code-block:: c++
1075
1076 std::vector<int> intVector;
1077 auto i = intVector.find(4);
1078
1079 auto stringSet = std::make_shared<std::set<std::string>>();
1080
1081 ``auto`` SHOULD NOT be used if a human reader cannot easily deduce the actual type.
1082
1083 .. code-block:: c++
1084
1085 auto x = foo(); // BAD if the declaration of foo() isn't nearby
1086
1087 ``const auto&`` SHOULD be used to represent constant reference types.
1088 ``auto&&`` SHOULD be used to represent mutable reference types.
1089
1090 .. code-block:: c++
1091
1092 std::list<std::string> strings;
1093
1094 for (const auto& str : strings) {
1095 statements; // cannot modify `str`
1096 }
1097 for (auto&& str : strings) {
1098 statements; // can modify `str`
1099 }
Junxiao Shia76bbc92015-03-23 11:05:37 -07001100
Davide Pesaventode2a1c22016-12-11 15:46:13 -050011013.30. Use the ``override`` or ``final`` specifier when overriding a virtual
1102member function or a virtual destructor.
Junxiao Shia76bbc92015-03-23 11:05:37 -07001103
Davide Pesaventode2a1c22016-12-11 15:46:13 -05001104 ``virtual`` MUST NOT be used along with ``final``, so that the compiler
1105 can generate an error when a final function does not override.
1106
1107 ``virtual`` SHOULD NOT be used along with ``override``, for consistency
1108 with ``final``.
Junxiao Shia76bbc92015-03-23 11:05:37 -07001109
1110 .. code-block:: c++
1111
1112 class Stream
1113 {
1114 public:
1115 virtual void
1116 open();
1117 };
1118
1119 class InputStream : public Stream
1120 {
1121 public:
Davide Pesaventode2a1c22016-12-11 15:46:13 -05001122 void
Junxiao Shia76bbc92015-03-23 11:05:37 -07001123 open() override;
1124 };
1125
1126 class Console : public InputStream
1127 {
1128 public:
Davide Pesaventode2a1c22016-12-11 15:46:13 -05001129 void
1130 open() final;
Junxiao Shia76bbc92015-03-23 11:05:37 -07001131 };
1132
Spyridon Mastorakis0d2ed2e2015-07-27 19:09:12 -070011333.31. The recommended way to throw an exception derived from ``std::exception`` is to use
1134the ``BOOST_THROW_EXCEPTION``
Davide Pesaventode2a1c22016-12-11 15:46:13 -05001135`macro <http://www.boost.org/doc/libs/1_54_0/libs/exception/doc/BOOST_THROW_EXCEPTION.html>`__.
Davide Pesaventobbca1b92015-12-25 20:06:00 +01001136Exceptions thrown using this macro will be augmented with additional diagnostic information,
1137including file name, line number, and function name from where the exception was thrown.