๐Ÿ“œ โฌ†๏ธ โฌ‡๏ธ

90 recommendations on the style of writing programs in C ++

From the translator. I was searching the Internet for a simple and easily applicable guideline on writing programs in C ++. I liked one of the options, and I decided to translate and publish it. If habra users well meet this topic, I can translate other related documents, as well as guidelines on writing code from other companies.

one Introduction


This document provides guidelines for writing C ++ programs.

The recommendations are based on established standards, collected from various sources, personal experience, particular requirements and the needs of certain projects, as well as from sources (see below).

But for the emergence of another list of recommendations, in addition to these sources, there are several reasons. The main reason is their excessive generalization, since it is often necessary to set private rules (especially naming rules). This document contains comments, which makes it more convenient to use when conducting code revisions than other existing documents. In addition, programming recommendations usually contain mixed descriptions of style problems and technical problems, which is not very convenient. This document does not contain any technical guidance on C ++, focusing on style issues.
')
Existing development environments can improve code readability by displaying access modifiers, code highlighting, automatic formatting, and others, but the programmer should not rely on these tools. Source code should be considered not only within the framework of the development environment used and should be written in such a way as to maximize readability regardless of the environment.

1.1 Document Format

The recommendations are grouped by topic and numbered so that they can be referenced during code revisions.

Recommendations are displayed as follows:

n. A short description of the recommendation.
//   ( )
, .

, ยซยป, .

1.2

: , .

2


1. , .

โ€” , , , . , .

2. , .

, . . , ( ), .

, .

3


3.1

3. , , , .

Line, SavingsAccount

C++.

4. , .

line, savingsAccount

C++. , , : Line line;

5. ( ) .

MAX_ITERATIONS, COLOR_RED, PI

C++. . โ€” :

  int getMaxIterations() // : MAX_ITERATIONS = 25
  {
    return 25;
  }

, .

6. , .

getName(), computeTotalWidth()

, .

7. .

model::analyzer, io::iomanager, common::math::geometry

C++.

8. .

template<class T> ...
template<class C, class D> ...

C++. .

9. .
exportHtmlSource(); // : exportHTMLSource();
openDvdPlayer();    // : openDVDPlayer();

, . dVD, hTML . ., . ; , ; , , , .

10. (::).

::mainWindow.open(), ::applicationContext.getName()

. .

11. private -.

class SomeClass {
  private:
    int length_;
}

, โ€” . . , , , .

- , , :

  void setDepth (int depth)
  {
    depth_ = depth;
  }

, โ€” . , , . , โ€” . , .

12. , .

void setTopic(Topic* topic)      // : void setTopic(Topic* value)
                                 // : void setTopic(Topic* aTopic)
                                 // : void setTopic(Topic* t)

void connect(Database* database) // : void connect(Database* db)
                                 // : void connect (Database* oracleDB)

. .

- , , .

:

  Point  startingPoint, centerPoint;
  Name   loginName;


13. -.

fileName;   //  : imyaFayla

.

14. , , , โ€” .

, , . , , , . i, j, k, l, m, n ( ), c d ( ).

15. , .

line.getLength();   //  : line.getLineLength();

, , .

( โ„– 16 .โ€” .)

3.2

17. get/set , .

employee.getName();
employee.setName(name);

matrix.getElement(2, 4);
matrix.setElement(2, 4, value);

C++. Java - .

18. compute , -.

valueSet->computeAverage();
matrix->computeInverse()

, .

19. find , - .

vertex.findNearestVertex();
matrix.findMinElement();

, , .

20. initialize , .

printer.initializeFontSet();

initialize, initialise. init.

21. , GUI, , .

mainWindow, propertiesDialog, widthScale, loginText,
leftScrollbar, mainForm, fileMenu, minLabel, exitButton, yesToggle  . .

, , , .

22. () .

vector<Point>  points;
int            values[];

, , .

23. n .

nPoints, nLines

, .

24. No .

tableNo, employeeNo

, .

i: iTable, iEmployee. , .

25. - i, j, k . .

for (int i = 0; i < nTables); i++) {
  :
}

for (vector<MyClass>::iterator i = list.begin(); i != list.end(); i++) {
  Element element = *i;
  ...
}

, .

j, k . . .

26. is () .

isSet, isVisible, isFinished, isFound, isOpen

C++, Java.

, status flag. isStatus isFlag , .

is : has, can should:

  bool hasLicense();
  bool canEvaluate();
  bool shouldSort();


27. .

get/set, add/remove, create/destroy, start/stop, insert/delete,
increment/decrement, old/new, begin/end, first/last, up/down, min/max,
next/previous, old/new, open/close, show/hide, suspend/resume,  . .

.

28. .

computeAverage();   // : compAvg();

. โ€” , , . :

cmd        command
cp         copy
pt         point
comp       compute
init       initialize
 . .


โ€” , - , /. . :

 HypertextMarkupLanguage      html
 CentralProcessingUnit        cpu
 PriceEarningRatio            pe
  . .


29. .

Line* line; //  : Line* pLine;
            //  : Line* linePtr;

C/C++ . , C++ , .

30. () , .

bool isError; // : isNoError
bool isFound; // : isNotFound

, , . !isNotFound.

31. โ€” .

enum Color {
  COLOR_RED,
  COLOR_GREEN,
  COLOR_BLUE
};

, , , .

: Color::RED, Airline::AIR_FRANCE . .

, , : enum Color {...}. , .

32. Exception.

class AccessException
{
  :
}

, .

33. (, - ) , , โ€” , ( void).

. , , , .

4


4.1

34. C++ .h () .hpp. .c++ (), .C, .cc .cpp.

MyClass.c++, MyClass.h

, C++.

35. () , .

MyClass.h, MyClass.c++


. โ€” , .

36. .

class MyClass
{
public:
  int getValue () {return value_;}  // !
  ...

private:
  int value_;
}

, . , , .

37. 80 .

80 โ€” , , ; , . .

38. (, TAB) .

, , , .

39. .

totalSum = a + b + c +
           d + e;

function (param1, param2,
          param3);

setText ("Long line split"
         "into two parts.");

for (int tableNo = 0; tableNo < nTables;
     tableNo += tableStep) {
  ...
}

, 80 , , . , .

:


4.2

40. .

#ifndef COM_COMPANY_MODULE_CLASSNAME_H
#define COM_COMPANY_MODULE_CLASSNAME_H
  :
#endif // COM_COMPANY_MODULE_CLASSNAME_H

. .

41. ( , โ€” ) . .

#include <fstream>
#include <iomanip>

#include <qt/qbutton.h>
#include <qt/qtextfield.h>

#include "com/company/ui/PropertiesDialog.h"
#include "com/company/ui/MainWindow.h"

. .

42. .

. , ยซยป - .

5


5.1

43. , , .

.

44. public, protected private . .

public, protected/private.

45. . .

floatValue = static_cast<float>(intValue); // : floatValue = intValue;

, , .

5.2

46. .

, . :

  int x, y, z;
  getCenter(&x, &y, &z);

, - .

47. .

, , . - .

48. .

C++ ( .โ€” ). () , โ€” .

49. public.

. private . โ€” , ( C). .

, C++ C; . .

( โ„– 50 .โ€” .)

51. C++ , .

float* x; //  : float *x; 
int& y;   //  : int &y;

, โ€” , , . C , C++ .

( โ„– 52 .โ€” .)

53. () .

if (nLines != 0)  //  : if (nLines)
if (value != 0.0) //  : if (value)

C++ , int float, , 0. .

, , , if (line == 0) if (line). C/C++, .

54. .

.

5.3

55. for() , .

sum = 0;                       // : for (i = 0, sum = 0; i < 100; i++)
for (i = 0; i < 100; i++)                sum += value[i];
  sum += value[i];

. , .

56. , , .

isDone = false;           //  : bool isDone = false;
while (!isDone) {         //      :
  :                       //      while (!isDone) {
}                         //        :
                          //      }


57. do-while.

, . , .

do-while . while for.

.

58. break continue .

, .

( โ„– 59 .โ€” .)

60. while (true) .

while (true) {
  :
}

for (;;) {  // !
  :
}

while (1) { // !
  :
}

. for (;;) ; , .

5.4

61. . .

bool isFinished = (elementNo < 0) || (elementNo > maxElement);
bool isRepeatedEntry = elementNo == lastElement;
if (isFinished || isRepeatedEntry) {
  :
}

// NOT:
if ((elementNo < 0) || (elementNo > maxElement)||
     elementNo == lastElement) {
  :
}

. , .

62. if, โ€” else.

bool isOk = readFile (fileName);
if (isOk) {
  :
}
else {
  :
}

, . .

63. .

if (isDone)       //  : if (isDone) doCleanup();
  doCleanup();

.

64. .

File* fileHandle = open(fileName, "w");
if (!fileHandle) {
  :
}

// :
if (!(fileHandle = open(fileName, "w"))) {
  :
}

. /++.

5.5

65. ยซยป . , 0 1, .

, . โ€” , .

66. .

double total = 0.0;    //  :  double total = 0;
double speed = 3.0e8;  //  :  double speed = 3e8;

double sum;
:
sum = (a + b) * 10.0;

. , .

( ) (sum) , .

67. , , .

double total = 0.5;  //  :  double total = .5;


C++ , , . , 0.5 โ€” , .5 ( 5).

68. .

int getValue()   // : getValue()
{
  :
}

, C++ , int. , , .

69. goto.

. (, ), .

70. ยซ0ยป ยซNULLยป.

NULL C C++.

6


6.1

71. .

for (i = 0; i < nElements; i++)
  a[i] = 0;

, . 4 , . 2, 3 4 ; 2 4 โ€” .

72. , 1 () 2, , 3. 2.

while (!done) {
  doSomething();
  done = moreToDo();
}


while (!done)
{
  doSomething();
  done = moreToDo();
}


while (!done)
  {
    doSomething();
    done = moreToDo();
  }

3 , .

73. :

class SomeClass : public BaseClass
{
  public:
    ...

  protected:
    ...

  private:
    ...
}

, .

74. :

void someMethod()
{
  ...
}

, .

75. if-else :

if (condition) {
  statements;
}

if (condition) {
  statements;
}
else {
   statements;
}

if (condition) {
  statements;
}
else if (condition) {
  statements;
}
else {
  statements;
}

, . else , , :

  if (condition) {
    statements;
  } else {
    statements;
  }

if-else . , , else.

76. for :

for (initialization; condition; update) {
  statements;
}

, .

77. for :

for (initialization; condition; update)
  ;

, . , , .

78. while :

while (condition) {
  statements;
}

, .

79. do-while :

do {
  statements;
} while (condition);

, .

80. switch :

switch (condition) {
  case ABC :
    statements;
    //  "break"

  case DEF :
    statements;
    break;

  case XYZ :
    statements;
    break;

  default :
    statements;
    break;
}

, case , . . - break, . , .

81. try-catch :

try {
  statements;
}
catch (Exception& exception) {
  statements;
}

, . , if-else, .

82. if-else , .

if (condition)
  statement;

while (condition)
  statement;

for (initialization; condition; update)
  statement;

.

83. .

void
MyClass::myMethod(void)
{
  :
}

.

6.2

84.

โ€” .
โ€” C++ .
โ€” .
โ€” .
โ€” for .

a = (b + c) * d; //  : a=(b+c)*d

while (true)   //  : while(true) 
{
  ...

doSomething(a, b, c, d);  //  : doSomething(a,b,c,d);

case 100 :  //  : case 100:

for (i = 0; i < 10; i++) {  //  : for(i=0;i<10;i++){
  ...

. . C++. .

85. , .

doSomething (currentFile);

. . , (doSomething()).

. : doSomething( currentFile );. ; , (doSomething( currentFile);).

86. .

Matrix4x4 matrix = new Matrix4x4();

double cosAngle = Math.cos(angle);
double sinAngle = Math.sin(angle);

matrix.setElement(1, 1,  cosAngle);
matrix.setElement(1, 2,  sinAngle);
matrix.setElement(2, 1, -sinAngle);
matrix.setElement(2, 2,  cosAngle);

multiply(matrix);

.

87. .

.

88. .

AsciiFile* file;
int        nPoints;
float      x, y;

. โ€” .

89. , .

if      (a == lowValue)    compueSomething();
else if (a == mediumValue) computeSomethingElse();
else if (a == highValue)   computeSomethingElseYet();

value = (potential        * oilDensity)   / constant1 +
        (depth            * waterDensity) / constant2 +
        (zCoordinateValue * gasDensity)   / constant3;

minPosition     = computeDistance(min,     x, y, z);
averagePosition = computeDistance(average, x, y, z);

switch (value) {
  case PHASE_OIL   : strcpy(phase, "Oil");   break;
  case PHASE_WATER : strcpy(phase, "Water"); break;
  case PHASE_GAS   : strcpy(phase, "Gas");   break;
}

, , .

6.3

90. , , , !

, .

91. .

โ€” .

92. // , .
// , 
//   .

, /* */ .

// , .

93. , , .

while (true) {       //  :  while (true) { 
  // Do something                          // Do something
  something();                               something();
}                                          }

, , .

94. JavaDoc.

Java Javadoc, HTML .

C++. , JavaDoc (., , Doc++ Doxygen).

7

Source: https://habr.com/ru/post/172091/


All Articles