CodingStandards.txt 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. 0. Formatting
  2. GOLDEN RULE: Follow the style of the existing code when you make changes.
  3. a. Use tabs for leading indentation
  4. - tab stops are every 4 characters.
  5. - One indentation level -> exactly one byte (i.e. a tab character) in the source file.
  6. - If you have run-on lines, indent as you would for a block.
  7. b. Line widths:
  8. - Don't worry about having lines of code > 80-char wide.
  9. - Lines of comments should be formatted according to ease of viewing, but simplicity is to be prefered over beauty.
  10. c. Don't use braces for condition-body one-liners.
  11. d. Never place condition bodies on same line as condition.
  12. e. Space between first paren and keyword, but *not* following first paren or preceeding final paren.
  13. f. No spaces when fewer than intra-expression three parens together; when three or more, space according to clarity.
  14. g. No spaces for subscripting or unary operators.
  15. h. No space before ':' but one after it, except in the ternary operator: one on both sides.
  16. i. Space all other operators.
  17. j. Braces, when used, always have their own lines and are at same indentation level as "parent" scope.
  18. (WRONG)
  19. if( a==b[ i ] ) { printf ("Hello\n"); }
  20. foo->bar(someLongVariableName,
  21. anotherLongVariableName,
  22. anotherLongVariableName,
  23. anotherLongVariableName,
  24. anotherLongVariableName);
  25. (RIGHT)
  26. if (a == b[i])
  27. printf("Hello\n"); // NOTE spaces used instead of tab here for clarity - first byte should be '\t'.
  28. foo->bar(
  29. someLongVariableName,
  30. anotherLongVariableName,
  31. anotherLongVariableName,
  32. anotherLongVariableName,
  33. anotherLongVariableName
  34. );
  35. 1. Namespaces;
  36. a. No "using namespace" declarations in header files.
  37. b. All symbols should be declared in a namespace except for final applications.
  38. c. Preprocessor symbols should be prefixed with the namespace in all-caps and an underscore.
  39. (WRONG)
  40. #include <cassert>
  41. using namespace std;
  42. tuple<float, float> meanAndSigma(vector<float> const& _v);
  43. (CORRECT)
  44. #include <cassert>
  45. std::tuple<float, float> meanAndSigma(std::vector<float> const& _v);
  46. 2. Preprocessor;
  47. a. File comment is always at top, and includes:
  48. - Copyright.
  49. - License (e.g. see COPYING).
  50. b. Never use #ifdef/#define/#endif file guards. Prefer #pragma once as first line below file comment.
  51. c. Prefer static const variable to value macros.
  52. d. Prefer inline constexpr functions to function macros.
  53. e. Split complex macro on multiple lines with '\'.
  54. 3. Capitalization;
  55. GOLDEN RULE: Preprocessor: ALL_CAPS; C++: camelCase.
  56. a. Use camelCase for splitting words in names, except where obviously extending STL/boost functionality in which case follow those naming conventions.
  57. b. The following entities' first alpha is upper case:
  58. - Type names.
  59. - Template parameters.
  60. - Enum members.
  61. - static const variables that form an external API.
  62. c. All preprocessor symbols (macros, macro argments) in full uppercase with underscore word separation.
  63. All other entities' first alpha is lower case.
  64. 4. Variable prefixes:
  65. a. Leading underscore "_" to parameter names (both normal and template).
  66. - Exception: "o_parameterName" when it is used exclusively for output. See 6(f).
  67. - Exception: "io_parameterName" when it is used for both input and output. See 6(f).
  68. b. Leading "c_" to const variables (unless part of an external API).
  69. c. Leading "g_" to global (non-const) variables.
  70. d. Leading "s_" to static (non-const, non-global) variables.
  71. 5. Error reporting:
  72. - Prefer exception to bool/int return type.
  73. 6. Declarations:
  74. a. {Typename} + {qualifiers} + {name}.
  75. b. Only one per line.
  76. c. Associate */& with type, not variable (at ends with parser, but more readable, and safe if in conjunction with (b)).
  77. d. Favour declarations close to use; don't habitually declare at top of scope ala C.
  78. e. Always pass non-trivial parameters with a const& suffix.
  79. f. If a function returns multiple values, use std::tuple (std::pair acceptable). Prefer not using */& arguments, except where efficiency requires.
  80. g. Never use a macro where adequate non-preprocessor C++ can be written.
  81. h. Make use of auto whenever type is clear or unimportant:
  82. - Always avoid doubly-stating the type.
  83. - Use to avoid vast and unimportant type declarations.
  84. - However, avoid using auto where type is not immediately obvious from the context, and especially not for arithmetic expressions.
  85. i. Don't pass bools: prefer enumerations instead.
  86. j. Prefer enum class to straight enum.
  87. (WRONG)
  88. const double d = 0;
  89. int i, j;
  90. char *s;
  91. float meanAndSigma(std::vector<float> _v, float* _sigma, bool _approximate);
  92. Derived* x(dynamic_cast<Derived*>(base));
  93. for (map<ComplexTypeOne, ComplexTypeTwo>::iterator i = l.begin(); i != l.end(); ++l) {}
  94. (CORRECT)
  95. enum class Accuracy
  96. {
  97. Approximate,
  98. Exact
  99. };
  100. double const d = 0;
  101. int i;
  102. int j;
  103. char* s;
  104. std::tuple<float, float> meanAndSigma(std::vector<float> const& _v, Accuracy _a);
  105. auto x = dynamic_cast<Derived*>(base);
  106. for (auto i = x.begin(); i != x.end(); ++i) {}
  107. 7. Structs & classes
  108. a. Structs to be used when all members public and no virtual functions.
  109. - In this case, members should be named naturally and not prefixed with 'm_'
  110. b. Classes to be used in all other circumstances.
  111. 8. Members:
  112. a. One member per line only.
  113. b. Private, non-static, non-const fields prefixed with m_.
  114. c. Avoid public fields, except in structs.
  115. d. Use override, final and const as much as possible.
  116. e. No implementations with the class declaration, except:
  117. - template or force-inline method (though prefer implementation at bottom of header file).
  118. - one-line implementation (in which case include it in same line as declaration).
  119. f. For a property 'foo'
  120. - Member: m_foo;
  121. - Getter: foo() [ also: for booleans, isFoo() ];
  122. - Setter: setFoo();
  123. 9. Naming
  124. a. Collection conventions:
  125. - -s means std::vector e.g. using MyTypes = std::vector<MyType>
  126. - -Set means std::set e.g. using MyTypeSet = std::set<MyType>
  127. - -Hash means std::unordered_set e.g. using MyTypeHash = std::unordered_set<MyType>
  128. b. Class conventions:
  129. - -Face means the interface of some shared concept. (e.g. FooFace might be a pure virtual class.)
  130. c. Avoid unpronouncable names;
  131. - If you need to shorten a name favour a pronouncable slice of the original to a scattered set of consonants.
  132. - e.g. Manager shortens to Man rather than Mgr.
  133. d. Avoid prefixes of initials (e.g. DON'T use IMyInterface, CMyImplementation)
  134. e. Find short, memorable & (at least semi-) descriptive names for commonly used classes or name-fragments.
  135. - A dictionary and thesaurus are your friends.
  136. - Spell correctly.
  137. - Think carefully about the class's purpose.
  138. - Imagine it as an isolated component to try to decontextualise it when considering its name.
  139. - Don't be trapped into naming it (purely) in terms of its implementation.
  140. 10. Type-definitions
  141. a. Prefer 'using' to 'typedef'. e.g. using ints = std::vector<int>; rather than typedef std::vector<int> ints;
  142. b. Generally avoid shortening a standard form that already includes all important information:
  143. - e.g. stick to shared_ptr<X> rather than shortening to ptr<X>.
  144. c. Where there are exceptions to this (due to excessive use and clear meaning), note the change prominently and use it consistently.
  145. - e.g. using Guard = std::lock_guard<std::mutex>; ///< Guard is used throughout the codebase since it's clear in meaning and used commonly.
  146. d. In general expressions should be roughly as important/semantically meaningful as the space they occupy.
  147. 11. Commenting
  148. a. Comments should be doxygen-compilable, using @notation rather than \notation.
  149. b. Document the interface, not the implementation.
  150. - Documentation should be able to remain completely unchanged, even if the method is reimplemented.
  151. - Comment in terms of the method properties and intended alteration to class state (or what aspects of the state it reports).
  152. - Be careful to scrutinise documentation that extends only to intended purpose and usage.
  153. - Reject documentation that is simply an English transaction of the implementation.
  154. 12. Include Headers
  155. Includes should go in increasing order of generality (libethereum -> libethcore -> libdevcrypto -> libdevcore -> boost -> STL). For example:
  156. #include <libethereum/Defaults.h>
  157. #include <libdevcrypto/SHA3.h>
  158. #include <libdevcore/Log.h>
  159. #include <libdevcore/Exceptions.h>
  160. #include <libdevcore/CommonData.h>
  161. #include <libdevcore/Common.h>
  162. #include <boost/filesystem.hpp>
  163. #include <string>
  164. See http://stackoverflow.com/questions/614302/c-header-order/614333#614333 for the reason: this makes it easier to find missing includes in header files.
  165. 13. Logging
  166. Logging should be performed at appropriate verbosities depending on the logging message.
  167. The more likely a message is to repeat (and thus cuase noise) the higher in verbosity it should be.
  168. Some rules to keep in mind:
  169. - Verbosity == 0 -> Reserved for important stuff that users must see and can understand.
  170. - Verbosity == 1 -> Reserved for stuff that users don't need to see but can understand.
  171. - Verbosity >= 2 -> Anything that is or might be displayed more than once every minute
  172. - Verbosity >= 3 -> Anything that only a developer would understand
  173. - Verbosity >= 4 -> Anything that is low-level (e.g. peer disconnects, timers being cancelled)
  174. 14. Recommended reading
  175. Herb Sutter and Bjarne Stroustrup
  176. - "C++ Core Guidelines" (https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md)
  177. Herb Sutter and Andrei Alexandrescu
  178. - "C++ Coding Standards: 101 Rules, Guidelines, and Best Practices"
  179. Scott Meyers
  180. - "Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition)"
  181. - "More Effective C++: 35 New Ways to Improve Your Programs and Designs"
  182. - "Effective Modern C++: 42 Specific Ways to Improve Your Use of C++11 and C++14"