5 Tips to Improve Your Code's Readability
Here are a few tips that will make your code easier to read and understand.
toc_collapse=0;
Contents
- Use tabs to indent your code
- Comment your code
- Use the ternary if operator ?:
- Compress huge, one-line statements
- Consistency, consistency, consistency...
Use tabs to indent your code
This one is a no-brainer. Code indentation is essential when it comes to readable code. There are a lot of ways of indenting your code and I am not going to advocate for one of them. I'm simply going to show you how you are not supposed to write code, and then, I'm going to show you one of the ways of properly indenting code.
int main()
{
int variable;
cin>>variable;
if(variable>2)
{
cout<<"Variable is bigger than 2: "<<variable;
}
else
{
cout<<"Not bigger than two: ";
while(variable--)
{
cout<<variable<<" ";
}
}
}
Now that's a very bad way of writing code because it is hard to follow. All the brackets are one under another, on the same vertical line. Brackets are used to enclose blocks of code that execute when certain conditions are met, and by indenting them properly a reader can determine the "depth" of a block easily and then jump up a few lines to see what conditions need to be met in order for that block to execute. If you do not indent your blocks properly people are going to have a hard time following your code and determining when a block executes.
In order to write readable code you must use tabs (the TAB key on your keyboard) to indent brackets and the instructions inside them.
int main() {
int variable;
cin >> variable;
if(variable > 2) {
cout << "Variable is bigger than 2: " << variable;
} else {
cout << "Not bigger than two: ";
while(variable--) {
cout << variable << " ";
}
}
}
Why tabs and not spaces? Well, tabs can be easier to manipulate, because when you want to "unindent" a block you just have to delete one character on each line -- a tab. But if you were using spaces, then you would have to delete a lot of spaces to "unindent" a line and it would get messy.
Comment your code
This is another no-brainer. Comments are really helpful for anyone reading the code because they uncover what the next piece of code does and prepare the reader to understand it better. Always, and I mean always, comment your code. You'll see how important this is when you'll look over some one else's code and you won't understand a thing because you have no idea what's the purpose of a function or a line of code. Even worse, you'll be appalled when you'll look over some code you wrote back in the days that you now seem unable to understand. Why? Because... there are no comments to guide you along the way.
When commenting the code, you must take the reader's perspective and ask yourself all the questions that might occur to a first-time reader. You must indicate what's the purpose of variables, of function calls or lines of code that might be unclear. You must carefully comment your functions' parameters and the assumptions the function makes about them, and your functions' return value and its meaning. Another thing to consider is consistency in your commenting style. You do want to keep a consistent format when commenting function definitions or class definitions because people are going to read a lot of these in your code and they should be presented with the same, easy to understand, comment layout each time.
Use the ternary if operator ?:
Not many people use the ?: operator in C++ and it is a shame because it can prove to be really handy when you need to write clean code.
The ?: operator replaces an if else statement, that would otherwise take up 3-5 lines of code, with a one line statement. What it means is that the following pieces of code are equivalent.
if (a > b) {
max = a;
} else {
max = b;
}
// Is equivalent to this...
max = (a > b) ? a : b;
I find that last line of code to be much more "expressive" and easier to read. It simply states so well that 'max' is equal to the greater value between 'a' and 'b'. Don't go out of line though. Nesting if-else statemnts using the ternary ?: operator will result in extremely hard to follow, nasty code. Don't do it.
Compress huge, one-line statements
You might have sometimes encountered this problem where you have a line of variable declarations or a cout statement that is way too long.
unsigned int numRows = 5, currentRow = 3, numColumns = 7, currentColumn = 5;
// Huge cout statement
cout << "The current number of rows is " << numRows << " and you are at row # " << currentRow << endl << "The current number of columns is " << numColumns << " and you are at column # " << currentColumn << endl;
So how do you make that code look nicer and easier to add comments to? Here's how I do it.
unsigned int
numRows = 5, // This also has the advantage
currentRow = 3, // that you can add comments
numColumns = 7, // very easily for each
currentColumn = 5; // variable individually
// Basically do the same thing for cout statements
cout << "The current number of rows is " << numRows
<< " and you are at row # " << currentRow << endl
<< "The current number of columns is " << numColumns
<< " and you are at column # " << currentColumn
<< endl;
// Write if statements with huge conditions like this
if (
(condition1 && condition2) ||
(condition2 && condition4) ||
!condition5
) {
doCertainStuff();
} else {
doOtherStuff();
}
// Same thing for function calls
HWND hwnd = CreateWindowEx(
0,
"WindowClassName",
"My test window",
WS_OVERLAPPED,
x,
y,
width,
height,
hwndParent,
0,
hInstance,
additionalData
);
In the case of the function call you could choose to have more than one parameter on a single line, for example you could have the x and y parameters and maybe the height and width on the same line since they don't take that much space and they're all related to the window's placement.
You don't have to adopt my style of course, some things might not look good to you, but I think you get the idea I'm trying to convey here.
Consistency, consistency, consistency...
I cannot emphasize how important it is that you respect a strict naming conventions when you name your functions, variables, and classes.
For instance, some people like to prepend the variable's type to a variables name, like in Hungarian Notation, which can prove to be useful for someone who skims through your code and wants to know what a variable does or represents.
You should also be consistent with your class naming convention. Usually class names are capitalized but you don't have to respect that establishment. Just make sure you stick to your choice throughout your code, whether you choose to capitalize or not, use underscores or not, etc.
Same thing goes for functions, some people like_them_like_this() and others PreferThemLikeThis(), it's a matter of style, but again, consistency is paramount.
Another tip I found to be useful when using capitalization in names, whether they're function, class or variable names, is to only capitalize the first letter in a word. For instance, if you were working on a HTTP protocol wrapper, then HttpRequest or HttpResponse would be better name choices for your classes rather than HTTPRequest or HTTPResponse.
Consistency applies to basically anything in your code, whether we're talking about naming variables or spacing out parameters in a function call or declaration. You need consistency in both naming and code layout.

Post new comment