All names should be meaningful, descriptive, and readable.
//Good
int wordCount;
//Bad
int c;
int wrCt;
Variable names should be camel-case, starting with a lowercase letter.
//Good
int flightCount;
//Bad
int FlightCount;
Function names should follow the same convention as variables.
//Good
int countFlights();
//Bad
int Count_Flights();
Classe names should be camel-case, starting with an uppercase letter.
//Good
class FlightPath {};
//Bad
class flightpath {};
Almost every function should have a descriptive comment preceding the declaration describing what the function does (not necessarily how it is done) unless the function is self-explanatory such as simple setter/getter functions.
Every class should have a descriptive comment at the top of the file describing what the class is and how it is used.
Inline comments should be expalantory but brief and concise, and should be placed above the line if more than a few words, or can be placed to the right of the line if only about 2-3 words. If placing multiple comments to the side, they should be aligned along the same column.
// Good
// Partition array and return pivot index
int pivot = partition(words, low, high);
quicksort(words, low, pivot - 1); // Sort left partition
quicksort(words, pivot + 1, high); // Sort right partition
// Bad
int pivot = partition(words, 0, words.size() - 1); // This will parition the array, placing the lower elements to the left of the pivot, and the higher elements to the right of the pivot, then it will return pivot index
quicksort(words, low, pivot - 1); // Sort left partition
quicksort(words, pivot + 1, high); // Sort right partition
It is up to you whether you want to use 2, 4 or 8 spaces, or tabs, but your choice of style must be consistent.
//Good
int collatz(int n) {
if (n % 2 == 0)
return n / 2;
else
return 3*n + 1;
}
//Bad
int collatz(int n) {
if (n % 2 == 0)
return n / 2;
else
return 3*n + 1;
}
Use whitespace to group logical steps together.
foo.setBar(1)
foo.setBaz(1)
bar.setBar(1)
bar.setBaz(1)
Place 1-2 lines between function declarations.
//Good
double foo(double x) {
return x * 2;
}
double bar(double x) {
return x * 3;
}
//Bad
double foo(double x) {
return x * 2;
}
double bar(double x) {
return x * 3;
}
Open braces should have a space before them, and conditionals should have spaces after the if keyword and around the else keyword.
void foo() {
if (flag) {
} else {
}
}
Lines should be at most 80 characters long to maximize readability.
Split long conditionals into multiple lines and align conditions
if (nodeA->left != nullptr && nodeB->right != nullptr) &&
(nodeA->left->value == nodeB->right->value) {
}
Wrap parameter lists that don't fit onto the next line and align parameters in function declarations and calls.
pair<string, vector<string>> reallyLongFunctionName(string foo, string bar,
vector<string> foobar,
pair<string, double> baz) {
}