Alexander Afanasyev | 766cea7 | 2014-04-24 19:16:42 -0700 | [diff] [blame] | 1 | ndn-cxx Code Style and Coding Guidelines |
| 2 | ======================================== |
Alexander Afanasyev | 3aeeaeb | 2014-04-22 23:34:23 -0700 | [diff] [blame] | 3 | |
| 4 | Based 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 | |
| 12 | 1. Code layout and file naming |
| 13 | ------------------------------ |
| 14 | |
| 15 | 1.1. The code layout should generally follow the GNU coding standard layout for C, |
| 16 | extended 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 | |
| 23 | 1.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 | |
| 44 | 1.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 | |
| 68 | 1.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 | |
| 97 | 1.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 | |
| 113 | 1.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 | |
| 155 | 1.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 | |
| 182 | 1.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 | |
| 199 | 1.9. A ``do-while`` statement should have the following form: |
| 200 | |
| 201 | .. code-block:: c++ |
| 202 | |
| 203 | do { |
| 204 | statements; |
| 205 | } while (condition); |
| 206 | |
| 207 | 1.10. A ``switch`` statement should have the following form: |
| 208 | |
| 209 | .. code-block:: c++ |
| 210 | |
| 211 | switch (condition) { |
| 212 | case ABC: |
| 213 | statements; |
| 214 | // Fallthrough |
| 215 | |
| 216 | case DEF: |
| 217 | statements; |
| 218 | break; |
| 219 | |
| 220 | case XYZ: |
| 221 | statements; |
| 222 | break; |
| 223 | |
| 224 | default: |
| 225 | statements; |
| 226 | break; |
| 227 | } |
| 228 | |
| 229 | or (less preferred): |
| 230 | |
| 231 | .. code-block:: c++ |
| 232 | |
| 233 | switch (condition) |
| 234 | { |
| 235 | case ABC: |
| 236 | statements; |
| 237 | // Fallthrough |
| 238 | |
| 239 | case DEF: |
| 240 | statements; |
| 241 | break; |
| 242 | |
| 243 | case XYZ: |
| 244 | statements; |
| 245 | break; |
| 246 | |
| 247 | default: |
| 248 | statements; |
| 249 | break; |
| 250 | } |
| 251 | |
| 252 | The explicit ``Fallthrough`` comment should be included whenever there is a case |
| 253 | statement without a break statement. Leaving the break out is a common error, and it |
| 254 | must be made clear that it is intentional when it is not there. |
| 255 | |
| 256 | 1.11. A ``try-catch`` statement should have the following form: |
| 257 | |
| 258 | .. code-block:: c++ |
| 259 | |
| 260 | try { |
| 261 | statements; |
| 262 | } |
| 263 | catch (Exception& exception) { |
| 264 | statements; |
| 265 | } |
| 266 | |
| 267 | or (less preferred): |
| 268 | |
| 269 | .. code-block:: c++ |
| 270 | |
| 271 | try |
| 272 | { |
| 273 | statements; |
| 274 | } |
| 275 | catch (Exception& exception) |
| 276 | { |
| 277 | statements; |
| 278 | } |
| 279 | |
| 280 | 1.12. The incompleteness of split lines must be made obvious. |
| 281 | |
| 282 | .. code-block:: c++ |
| 283 | |
| 284 | totalSum = a + b + c + |
| 285 | d + e; |
| 286 | function(param1, param2, |
| 287 | param3); |
| 288 | for (int tableNo = 0; tableNo < nTables; |
| 289 | tableNo += tableStep) { |
| 290 | ... |
| 291 | } |
| 292 | |
| 293 | Split lines occurs when a statement exceed the 80 column limit given above. It is |
| 294 | difficult to give rigid rules for how lines should be split, but the examples above should |
| 295 | give a general hint.In general: |
| 296 | |
| 297 | * Break after a comma. |
| 298 | * Break after an operator. |
| 299 | * Align the new line with the beginning of the expression on the previous line. |
| 300 | |
| 301 | Exceptions: |
| 302 | |
| 303 | * The following is the standard practice with operator<<: |
| 304 | |
| 305 | .. code-block:: c++ |
| 306 | |
| 307 | std::cout << "Something here " |
| 308 | << "Something there" << std::endl; |
| 309 | |
| 310 | 1.13. When class variables need to be initialized in the constructor, the initialization |
| 311 | should take the following form: |
| 312 | |
| 313 | .. code-block:: c++ |
| 314 | |
| 315 | SomeClass::SomeClass(int value, const std::string& string) |
| 316 | : m_value(value) |
| 317 | , m_string(string) |
| 318 | ... |
| 319 | { |
| 320 | } |
| 321 | |
| 322 | Each initialization should be put on a separate line, starting either with the colon |
| 323 | for the first initialization or with comma for all subsequent initializations. |
| 324 | |
| 325 | 2. Naming Conventions |
| 326 | --------------------- |
| 327 | |
| 328 | 2.1. C++ header files should have the extension ``.hpp``. Source files should have the |
| 329 | extension ``.cpp`` |
| 330 | |
| 331 | File names should be all lower case. If the class name |
| 332 | is a composite of several words, each word in a file name should be separated with a |
| 333 | dash (-). A class should be declared in a header file and defined in a source file |
| 334 | where the name of the files match the name of the class. |
| 335 | |
| 336 | :: |
| 337 | |
| 338 | my-class.hpp, my-class.cpp |
| 339 | |
| 340 | |
| 341 | 2.2. Names representing types must be written in English in mixed case starting with upper case. |
| 342 | |
| 343 | .. code-block:: c++ |
| 344 | |
| 345 | class MyClass; |
| 346 | class Line; |
| 347 | class SavingsAccount; |
| 348 | |
| 349 | 2.3. Variable names must be written in English in mixed case starting with lower case. |
| 350 | |
| 351 | .. code-block:: c++ |
| 352 | |
| 353 | MyClass myClass; |
| 354 | Line line; |
| 355 | SavingsAccount savingsAccount; |
| 356 | int theAnswerToLifeTheUniverseAndEverything; |
| 357 | |
| 358 | 2.4. Named constants (including enumeration values) must be all uppercase using underscore |
| 359 | to separate words. |
| 360 | |
| 361 | .. code-block:: c++ |
| 362 | |
| 363 | const int MAX_ITERATIONS = 25; |
| 364 | const std::string COLOR_RED = "red"; |
| 365 | static const double PI = 3.14; |
| 366 | |
| 367 | In some cases, it is a better (or is the only way for complex constants in header-only |
| 368 | classes) to implement the value as a method: |
| 369 | |
| 370 | .. code-block:: c++ |
| 371 | |
| 372 | int |
| 373 | getMaxIterations() |
| 374 | { |
| 375 | return 25; |
| 376 | } |
| 377 | |
| 378 | 2.5. Names representing methods or functions must be commands starting with a verb and |
| 379 | written in mixed case starting with lower case. |
| 380 | |
| 381 | .. code-block:: c++ |
| 382 | |
| 383 | std::string |
| 384 | getName() |
| 385 | { |
| 386 | ... |
| 387 | } |
| 388 | |
| 389 | double |
| 390 | computeTotalWidth() |
| 391 | { |
| 392 | ... |
| 393 | } |
| 394 | |
| 395 | 2.6. Names representing namespaces should be all lowercase. |
| 396 | |
| 397 | .. code-block:: c++ |
| 398 | |
| 399 | namespace model { |
| 400 | namespace analyzer { |
| 401 | |
| 402 | ... |
| 403 | |
| 404 | } // namespace analyzer |
| 405 | } // namespace model |
| 406 | |
| 407 | 2.7. Names representing generic template types should be a single uppercase letter |
| 408 | |
| 409 | .. code-block:: c++ |
| 410 | |
| 411 | template<class T> ... |
| 412 | template<class C, class D> ... |
| 413 | |
| 414 | However, when template parameter represents a certain concept and expected to have a |
| 415 | certain interface, the name should be explicitly spelled out: |
| 416 | |
| 417 | .. code-block:: c++ |
| 418 | |
| 419 | template<class FaceBase> ... |
| 420 | template<class Packet> ... |
| 421 | |
| 422 | 2.8. Abbreviations and acronyms must not be uppercase when used as name. |
| 423 | |
| 424 | .. code-block:: c++ |
| 425 | |
| 426 | exportHtmlSource(); // NOT: exportHTMLSource(); |
| 427 | openDvdPlayer(); // NOT: openDVDPlayer(); |
| 428 | |
| 429 | 2.9. Global variables should have ``g_`` prefix |
| 430 | |
| 431 | .. code-block:: c++ |
| 432 | |
| 433 | g_mainWindow.open(); |
| 434 | g_applicationContext.getName(); |
| 435 | |
| 436 | In general, the use of global variables should be avoided. Consider using singleton |
| 437 | objects instead. |
| 438 | |
| 439 | 2.10. Private class variables should have ``m_`` prefix. Static class variables should have |
| 440 | ``s_`` prefix. |
| 441 | |
| 442 | .. code-block:: c++ |
| 443 | |
| 444 | class SomeClass |
| 445 | { |
| 446 | private: |
| 447 | int m_length; |
| 448 | |
| 449 | static std::string s_name; |
| 450 | }; |
| 451 | |
| 452 | |
| 453 | 2.11. Variables with a large scope should have long (explicit) names, variables with a small |
| 454 | scope can have short names. |
| 455 | |
| 456 | Scratch variables used for temporary storage or indices are best kept short. A |
| 457 | programmer reading such variables should be able to assume that its value is not used |
| 458 | outside of a few lines of code. Common scratch variables for integers are ``i``, |
| 459 | ``j``, ``k``, ``m``, ``n`` and for characters ``c`` and ``d``. |
| 460 | |
| 461 | 2.12. The name of the object is implicit, and should be avoided in a method name. |
| 462 | |
| 463 | .. code-block:: c++ |
| 464 | |
| 465 | line.getLength(); // NOT: line.getLineLength(); |
| 466 | |
| 467 | The latter seems natural in the class declaration, but proves superfluous in use, as |
| 468 | shown in the example. |
| 469 | |
| 470 | 2.13. The terms ``get/set`` must be used where an attribute is accessed directly. |
| 471 | |
| 472 | .. code-block:: c++ |
| 473 | |
| 474 | employee.getName(); |
| 475 | employee.setName(name); |
| 476 | |
| 477 | matrix.getElement(2, 4); |
| 478 | matrix.setElement(2, 4, value); |
| 479 | |
| 480 | 2.14. The term ``compute`` can be used in methods where something is computed. |
| 481 | |
| 482 | .. code-block:: c++ |
| 483 | |
| 484 | valueSet.computeAverage(); |
| 485 | matrix.computeInverse() |
| 486 | |
| 487 | Give the reader the immediate clue that this is a potentially time-consuming operation, |
| 488 | and if used repeatedly, he might consider caching the result. Consistent use of the term |
| 489 | enhances readability. |
| 490 | |
| 491 | 2.15. The term ``find`` can be used in methods where something is looked up. |
| 492 | |
| 493 | .. code-block:: c++ |
| 494 | |
| 495 | vertex.findNearestVertex(); |
| 496 | matrix.findMinElement(); |
| 497 | |
| 498 | Give the reader the immediate clue that this is a simple look up method with a minimum |
| 499 | of computations involved. Consistent use of the term enhances readability. |
| 500 | |
| 501 | 2.16. Plural form should be used on names representing a collection of objects. |
| 502 | |
| 503 | .. code-block:: c++ |
| 504 | |
| 505 | vector<Point> points; |
| 506 | int values[]; |
| 507 | |
| 508 | Enhances readability since the name gives the user an immediate clue of the type of |
| 509 | the variable and the operations that can be performed on its elements. |
| 510 | |
| 511 | 2.17. The prefix ``n`` should be used for variables representing a number of objects. |
| 512 | |
| 513 | .. code-block:: c++ |
| 514 | |
| 515 | nPoints, nLines |
| 516 | |
| 517 | The notation is taken from mathematics where it is an established convention for |
| 518 | indicating a number of objects. |
| 519 | |
| 520 | |
| 521 | 2.18. The suffix ``No`` should be used for variables representing an entity number. |
| 522 | |
| 523 | .. code-block:: c++ |
| 524 | |
| 525 | tableNo, employeeNo |
| 526 | |
| 527 | The notation is taken from mathematics where it is an established convention for |
| 528 | indicating an entity number. An elegant alternative is to prefix such variables with |
| 529 | an ``i``: ``iTable``, ``iEmployee``. This effectively makes them named iterators. |
| 530 | |
| 531 | 2.19. The prefix ``is``, ``has``, ``need``, or similar should be used for boolean variables and |
| 532 | methods. |
| 533 | |
| 534 | .. code-block:: c++ |
| 535 | |
| 536 | isSet, isVisible, isFinished, isFound, isOpen |
| 537 | needToConvert, needToFinish |
| 538 | |
| 539 | 2.20. Complement names must be used for complement operations, reducing complexity by |
| 540 | symmetry. |
| 541 | |
| 542 | :: |
| 543 | |
| 544 | get/set, add/remove, create/destroy, start/stop, insert/delete, |
| 545 | increment/decrement, old/new, begin/end, first/last, up/down, min/max, |
| 546 | next/previous (and commonly used next/prev), open/close, show/hide, |
| 547 | suspend/resume, etc. |
| 548 | |
| 549 | Pair ``insert/erase`` should be preferred. ``insert/delete`` can also be used if it |
| 550 | does not conflict with C++ delete keyword. |
| 551 | |
| 552 | 2.21. Variable names should not include reference to variable type (do not use Hungarian |
| 553 | notation). |
| 554 | |
| 555 | .. code-block:: c++ |
| 556 | |
| 557 | Line* line; // NOT: Line* pLine; |
| 558 | // NOT: Line* linePtr; |
| 559 | |
| 560 | size_t nPoints; // NOT lnPoints |
| 561 | |
| 562 | char* name; // NOT szName |
| 563 | |
| 564 | 2.22. Negated boolean variable names should be avoided. |
| 565 | |
| 566 | .. code-block:: c++ |
| 567 | |
| 568 | bool isError; // NOT: isNoError |
| 569 | bool isFound; // NOT: isNotFound |
| 570 | |
| 571 | 2.23. Enumeration constants recommended to prefix with a common type name. |
| 572 | |
| 573 | .. code-block:: c++ |
| 574 | |
| 575 | enum Color { |
| 576 | COLOR_RED, |
| 577 | COLOR_GREEN, |
| 578 | COLOR_BLUE |
| 579 | }; |
| 580 | |
| 581 | 2.24. Exceptions can be suffixed with either ``Exception`` (e.g., ``SecurityException``) or |
| 582 | ``Error`` (e.g., ``SecurityError``). |
| 583 | |
| 584 | The recommended method is to declare exception class ``Exception`` or ``Error`` as an |
| 585 | inner class, from which the exception is thrown. For example, when declaring class |
| 586 | ``Foo`` that can throw errors, one can write the following: |
| 587 | |
| 588 | .. code-block:: c++ |
| 589 | |
| 590 | #include <stdexcept> |
| 591 | |
| 592 | class Foo |
| 593 | { |
| 594 | class Error : public std::runtime_error |
| 595 | { |
| 596 | public: |
| 597 | explicit |
| 598 | Error(const std::string& what) |
| 599 | : std::runtime_error(what) |
| 600 | { |
| 601 | } |
| 602 | }; |
| 603 | }; |
| 604 | |
| 605 | In addition to that, if class Foo is a base class or interface for some class |
| 606 | hierarchy, then child classes should should define their own ``Error`` or |
| 607 | ``Exception`` classes that are inherited from the parent's Error class. |
| 608 | |
| 609 | |
| 610 | 2.25. Functions (methods returning something) should be named after what they return and |
| 611 | procedures (void methods) after what they do. |
| 612 | |
| 613 | Increase readability. Makes it clear what the unit should do and especially all the |
| 614 | things it is not supposed to do. This again makes it easier to keep the code clean of |
| 615 | side effects. |
| 616 | |
| 617 | 3. Miscellaneous |
| 618 | ---------------- |
| 619 | |
| 620 | 3.1. Exceptions can be used in the code, but should be used only in exceptional cases and |
| 621 | not in the primary processing path. |
| 622 | |
| 623 | 3.2. Header files must contain an include guard. |
| 624 | |
| 625 | For example, header file located in ``module/class-name.hpp`` or in |
| 626 | ``src/module/class-name.hpp`` should have header guard in the following form: |
| 627 | |
| 628 | .. code-block:: c++ |
| 629 | |
| 630 | #ifndef APP_MODULE_CLASS_NAME_HPP |
| 631 | #define APP_MODULE_CLASS_NAME_HPP |
| 632 | ... |
| 633 | #endif // APP_MODULE_CLASS_NAME_HPP |
| 634 | |
| 635 | The name should follow the location of the file inside the source tree and prevents |
| 636 | naming conflicts. Header guard should be prefixed with the application/library name |
| 637 | to avoid conflicts with other packaged and libraries. |
| 638 | |
| 639 | 3.3. Header files which are in the same source distribution should be included in |
| 640 | ``"quotes"``, if possible with a path relative to the source file. Header files for |
| 641 | system and other external libraries should be included in ``<angle brackets>``. |
| 642 | |
| 643 | .. code-block:: c++ |
| 644 | |
| 645 | #include <string> |
| 646 | #include <boost/lexical_cast.hpp> |
| 647 | |
| 648 | #include "util/random.hpp" |
| 649 | |
| 650 | 3.4. Include statements should be sorted and grouped. Sorted by their hierarchical position |
| 651 | in the system with low level files included first. Leave an empty line between groups |
| 652 | of include statements. |
| 653 | |
| 654 | .. code-block:: c++ |
| 655 | |
| 656 | #include <fstream> |
| 657 | #include <iomanip> |
| 658 | |
| 659 | #include <boost/lexical_cast.hpp> |
| 660 | #include <boost/regex.hpp> |
| 661 | |
| 662 | #include "detail/pending-interest.hpp" |
| 663 | #include "util/random.hpp" |
| 664 | |
| 665 | |
| 666 | 3.5. Types that are local to one file only can be declared inside that file. |
| 667 | |
| 668 | |
| 669 | 3.6. Implicit conversion is generally allowed. |
| 670 | |
| 671 | Implicit conversion between integer and floating point numbers can cause problems and |
| 672 | should be avoided. |
| 673 | |
| 674 | Implicit conversion in single-argument constructor is usually undesirable. Therefore, all |
| 675 | single-argument constructors should be marked 'explicit', unless implicit conversion is |
| 676 | desirable. In that case, a comment should document the reason. |
| 677 | |
| 678 | Avoid C-style casts. Use ``static_cast``, ``dynamic_cast``, ``reinterpret_cast``, |
| 679 | ``const_cast`` instead where appropriate. Use ``static_pointer_cast``, |
| 680 | ``dynamic_pointer_cast``, ``const_pointer_cast`` when dealing with ``shared_ptr``. |
| 681 | |
| 682 | |
| 683 | 3.7. Variables should be initialized where they are declared. |
| 684 | |
| 685 | This ensures that variables are valid at any time. Sometimes it is impossible to |
| 686 | initialize a variable to a valid value where it is declared: |
| 687 | |
| 688 | .. code-block:: c++ |
| 689 | |
| 690 | int x, y, z; |
| 691 | getCenter(&x, &y, &z); |
| 692 | |
| 693 | In these cases it should be left uninitialized rather than initialized to some phony |
| 694 | value. |
| 695 | |
| 696 | 3.8. In most cases, class instance variables should not be declared public. |
| 697 | |
| 698 | The concepts of information hiding and encapsulation are violated by public variables. Use |
| 699 | private variables and access methods instead. |
| 700 | |
| 701 | Exceptions to this rule: |
| 702 | |
| 703 | * when the class is essentially a dumb data structure with no or minimal behavior |
| 704 | (equivalent to a C struct, also known as PODS). In this case it is appropriate to make |
| 705 | the instance variables public by using struct. |
| 706 | |
| 707 | * when the class is used only inside the compilation unit, e.g., when implementing pImpl |
| 708 | idiom (aka Bridge pattern) or similar cases. |
| 709 | |
| 710 | |
| 711 | 3.9. C++ pointers and references should have their reference symbol next to the type rather |
| 712 | than to the name. |
| 713 | |
| 714 | .. code-block:: c++ |
| 715 | |
| 716 | float* x; // NOT: float *x; |
| 717 | int& y; // NOT: int &y; |
| 718 | |
| 719 | 3.10. Implicit test for 0 should not be used other than for boolean variables and pointers. |
| 720 | |
| 721 | .. code-block:: c++ |
| 722 | |
| 723 | if (nLines != 0) // NOT: if (nLines) |
| 724 | if (value != 0.0) // NOT: if (value) |
| 725 | |
| 726 | 3.11. When checking if ``shared_ptr`` points to an object, explicit ``static_cast<bool>`` |
| 727 | must be used. |
| 728 | |
| 729 | ``shared_ptr`` in C++11 (unlike ``boost::shared_ptr``) does not have implicit |
| 730 | conversion to bool. |
| 731 | |
| 732 | 3.12. Loop variables should be initialized immediately before the loop. |
| 733 | |
| 734 | .. code-block:: c++ |
| 735 | |
| 736 | isDone = false; // NOT: bool isDone = false; |
| 737 | while (!isDone) { // // other stuff |
| 738 | : // while (!isDone) { |
| 739 | } // : |
| 740 | // } |
| 741 | |
| 742 | 3.13. The form while (true) should be used for infinite loops. |
| 743 | |
| 744 | .. code-block:: c++ |
| 745 | |
| 746 | while (true) { |
| 747 | ... |
| 748 | } |
| 749 | |
| 750 | // NOT: |
| 751 | for (;;) { // NO! |
| 752 | : |
| 753 | } |
| 754 | while (1) { // NO! |
| 755 | : |
| 756 | } |
| 757 | |
| 758 | 3.14. Complex conditional expressions must be avoided. Introduce temporary boolean variables |
| 759 | instead. |
| 760 | |
| 761 | .. code-block:: c++ |
| 762 | |
| 763 | bool isFinished = (elementNo < 0) || (elementNo > maxElement); |
| 764 | bool isRepeatedEntry = elementNo == lastElement; |
| 765 | if (isFinished || isRepeatedEntry) { |
| 766 | ... |
| 767 | } |
| 768 | |
| 769 | // NOT: |
| 770 | // if ((elementNo < 0) || (elementNo > maxElement) || elementNo == lastElement) { |
| 771 | // ... |
| 772 | // } |
| 773 | |
| 774 | By assigning boolean variables to expressions, the program gets automatic |
| 775 | documentation. The construction will be easier to read, debug and maintain. |
| 776 | |
| 777 | 3.15. The conditional should be put on a separate line. |
| 778 | |
| 779 | .. code-block:: c++ |
| 780 | |
| 781 | if (isDone) // NOT: if (isDone) doCleanup(); |
| 782 | doCleanup(); |
| 783 | |
| 784 | This is for debugging purposes. When writing on a single line, it is not apparent |
| 785 | whether the test is really true or not. |
| 786 | |
| 787 | 3.16. Assignment statements in conditionals must be avoided. |
| 788 | |
| 789 | .. code-block:: c++ |
| 790 | |
| 791 | File* fileHandle = open(fileName, "w"); |
| 792 | if (!fileHandle) { |
| 793 | ... |
| 794 | } |
| 795 | |
| 796 | // NOT |
| 797 | // if (!(fileHandle = open(fileName, "w"))) { |
| 798 | // .. |
| 799 | // } |
| 800 | |
| 801 | 3.17. The use of magic numbers in the code should be avoided. Numbers other than 0 and 1 |
| 802 | should be considered declared as named constants instead. |
| 803 | |
| 804 | If the number does not have an obvious meaning by itself, the readability is enhanced |
| 805 | by introducing a named constant instead. A different approach is to introduce a method |
| 806 | from which the constant can be accessed. |
| 807 | |
| 808 | 3.18. Floating point constants should always be written with decimal point, at least one |
| 809 | decimal, and without omitting 0 before decimal point. |
| 810 | |
| 811 | .. code-block:: c++ |
| 812 | |
| 813 | double total = 0.0; // NOT: double total = 0; |
| 814 | double someValue = 0.1; // NOT double someValue = .1; |
| 815 | double speed = 3.0e8; // NOT: double speed = 3e8; |
| 816 | double sum; |
| 817 | ... |
| 818 | sum = (a + b) * 10.0; |
| 819 | |
| 820 | 3.19. ``goto`` should not be used. |
| 821 | |
| 822 | Goto statements violate the idea of structured code. Only in some very few cases (for |
| 823 | instance breaking out of deeply nested structures) should goto be considered, and only if |
| 824 | the alternative structured counterpart is proven to be less readable. |
| 825 | |
| 826 | 3.20. "0" should be used instead of "NULL". |
| 827 | |
| 828 | 3.21. Logical units within a block should be separated by one blank line. |
| 829 | |
| 830 | .. code-block:: c++ |
| 831 | |
| 832 | Matrix4x4 matrix = new Matrix4x4(); |
| 833 | |
| 834 | double cosAngle = Math.cos(angle); |
| 835 | double sinAngle = Math.sin(angle); |
| 836 | |
| 837 | matrix.setElement(1, 1, cosAngle); |
| 838 | matrix.setElement(1, 2, sinAngle); |
| 839 | matrix.setElement(2, 1, -sinAngle); |
| 840 | matrix.setElement(2, 2, cosAngle); |
| 841 | |
| 842 | multiply(matrix); |
| 843 | |
| 844 | Enhance readability by introducing white space between logical units of a block. |
| 845 | |
| 846 | 3.22. Variables in declarations can be left aligned. |
| 847 | |
| 848 | .. code-block:: c++ |
| 849 | |
| 850 | AsciiFile* file; |
| 851 | int nPoints; |
| 852 | float x, y; |
| 853 | |
| 854 | Enhance readability. The variables are easier to spot from the types by alignment. |
| 855 | |
| 856 | 3.23. Use alignment wherever it enhances readability. |
| 857 | |
| 858 | .. code-block:: c++ |
| 859 | |
| 860 | value = (potential * oilDensity) / constant1 + |
| 861 | (depth * waterDensity) / constant2 + |
| 862 | (zCoordinateValue * gasDensity) / constant3; |
| 863 | |
| 864 | minPosition = computeDistance(min, x, y, z); |
| 865 | averagePosition = computeDistance(average, x, y, z); |
| 866 | |
| 867 | There are a number of places in the code where white space can be included to enhance |
| 868 | readability even if this violates common guidelines. Many of these cases have to do |
| 869 | with code alignment. General guidelines on code alignment are difficult to give, but |
| 870 | the examples above should give a general clue. |
| 871 | |
| 872 | 3.24. All comments should be written in English. |
| 873 | |
| 874 | In an international environment English is the preferred language. |
| 875 | |
Alexander Afanasyev | dfa52c4 | 2014-04-24 21:10:11 -0700 | [diff] [blame] | 876 | 3.25. Use ``//`` for all comments, including multi-line comments. |
Alexander Afanasyev | 3aeeaeb | 2014-04-22 23:34:23 -0700 | [diff] [blame] | 877 | |
| 878 | .. code-block:: c++ |
| 879 | |
| 880 | // Comment spanning |
| 881 | // more than one line. |
| 882 | |
| 883 | Since multilevel C-commenting is not supported, using ``//`` comments ensure that it |
| 884 | is always possible to comment out entire sections of a file using ``/* */`` for |
| 885 | debugging purposes etc. |
| 886 | |
| 887 | There should be a space between the ``//`` and the actual comment, and comments should |
| 888 | always start with an upper case letter and end with a period. |
| 889 | |
| 890 | However, method and class documentation comments should use ``/** */`` style for |
| 891 | Doxygen, JavaDoc and JSDoc. |
| 892 | |
| 893 | 3.26. Comments should be included relative to their position in the code. |
| 894 | |
| 895 | .. code-block:: c++ |
| 896 | |
| 897 | while (true) { |
| 898 | // Do something |
| 899 | something(); |
| 900 | } |
| 901 | |
| 902 | // NOT: |
| 903 | while (true) { |
| 904 | // Do something |
| 905 | something(); |
| 906 | } |
| 907 | |
| 908 | This is to avoid that the comments break the logical structure of the program. |