Writing Clean Code — Part 2

Logeshvar L
FAUN — Developer Community 🐾
8 min readAug 16, 2021

--

Making life easier by writing easily readable code

In the last post, we saw how important it is to properly name your variables, and how easier it is to read and understand the code that way. As the emphasis on naming is more clear now, let’s have a look into the other practices as the next part.

www.xkcd.com

In this post, I’ll tell you about the common best practices for using comments in your code and about code formatting in each of your files. When to use comments, when not to use comments and the more important question,

Do we really need comments?

Did this question arise in your mind ever? If yes, great. I hope you’d have found the answer by now. If not, nothing bad, I’ll answer that. We already have proper naming of everything in place. So our code is already more readable. Then do we really need any more comments? I say this because so far all I learnt was that comments are used to tell what is happening and help the reader to get an idea of what is done. And I believe most of us are fed with this kind of knowledge only. To say an example, we simply add comments like:

These comments do nothing but explain the obvious. If you think from a different perspective, these comments are nothing but redundant information. They just say explicitly what the code is doing.

Do you think this is a really good way of programming? No.
But do we get rid of comments, completely? No.

Comments do have some significance and they’re created to serve a purpose. There are places that can only be filled by using comments. Let’s discuss these situations in more depth.

/*avoid comments*/

As I said already, comments are typically bad. Try to avoid comments in your code as much as possible. As discussed already, one is giving redundant information just for the sake of making it more clear, but in an unknown way of making it worse.

Another reason would be that comments can sometimes be misleading. You’d write some comments initially, but with each version, the functionality of the code might change. As code keeps changing, we lose focus on comments and forget to update them.

You could see how misleading that comment is. If any developer starts reading the comment and looks at the code, just think of their reaction. Always strive towards making the code self-explanatory.

Another bad way of using comments in code is, using comments as a divider to separate different parts of code. We do that thinking it makes our code cuter. But it doesn’t actually.

I saved the worst one for the last. Most of us do this, not once but a lot.

Ugh, having commented out code. That’s the worst. If you don’t want a snippet of code, just remove it. If you are not using it now but might need it in the future, still remove it because of YAGNI. These are places where you should completely avoid comments. But still, certain situations need comments and they’re unavoidable, let’s discuss those.

/*add comments here*/

I hope you’re familiar with code licensing. Even for open source libraries, there is a code licensing process to make it free to use for others.

# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==================================================================

The above code is taken from the TensorFlow Github page. This is an example of using comments to display license information. So it is acceptable to use comments in this situation.

In the above case, it is a very complex regular expression, which takes a lot of effort for the reader to understand. But using a comment here makes it really easy to read and quickly understand. So, it is ok to use comments here too.

This also applies to documentation comments. For APIs documentation, it is acceptable to give some comments about how it works, when you’re building some form of a library or framework and other people are going to use it. The documentation is really helpful in that case.

Also in rare cases, warnings next to some code could make sense — for example, if a unit test may take a long time to complete or if a certain functionality won’t work in certain environments.

Adding “Todo” notes is okay as well, but you shouldn’t overdo it.

Although it’s better to implement features completely, or in incremental steps without “Todo” comments, leaving a few “Todo” comments here and there won’t hurt, especially because modern IDEs make it easy to find these notes.

Still, there is no benefit to your code readability (or your overall code quality), if you leave a bunch of “Todo” comments everywhere!

Code Formatting

Another important concept I’ll discuss here is the concept of proper code formatting. Formatting is nothing but the correct alignment and grouping of code, to make it cleaner and easily readable.

There are two kinds of formatting we’ll see — vertical and horizontal formatting of code.

Vertical formatting is all about providing proper vertical spaces, which is nothing but adding sufficient blank lines, which reduces the confusion and properly groups the code based on relativity between each block of code.

The above code uses good names and is not exhaustively long — still it can be challenging to digest. The close grouping of code can make it really difficult for the reader to understand.

The above is also the same code snippet, but with proper code spacing and sufficient blank lines. This is now more readable.

There are two concepts to be remembered when adding blank lines.
Vertical density: Related concepts/codes should be placed next to each other.
Vertical distance: Concepts that are not closely related should be separated.

Here, we have two main concepts in the signup function: Validation and creating the new user in the database. Thus, a blank line should separate the two concepts. In contrast, creating the user object and then calling saveToDatabase() on it belong together, thus no blank line should appear between them.

If we had multiple functions, then functions that call other functions should be kept close together — with blank lines in between but not on different ends of the code file. If functions are not directly working together (i.e. not directly calling each other) it is okay if there is more space (e.g. other functions) in between.

Ordering Functions & Methods

When it comes to ordering functions and methods, it is a good practice to follow the “stepdown rule”.

The function validate() which is called by function login() should be (closely) below function login() to promote more vertical density.

Splitting Code Across Files

If your code file gets bigger and/ or if you have a lot of different “things” in one file (e.g. multiple class definitions), it is considered good practice to split that code across multiple files and then use import and export statements to connect your code. This ensures that your individual code files as a whole stay readable.

Horizontal Formatting is all about maintaining minimal horizontal spacing and keeping it short and more readable.

Breaking long lines into multiple lines

Do not use extremely long lines of code and make it more difficult to understand and grasp even if it is a simple functionality.

This is too long and too much code for a single line. Instead, split it into multiple lines of code and make it easier to read and understand

The above snippet is doing the same logic but is easier to read.

Using Short Names

Names should be descriptive — you learned that. But you shouldn’t waste space and make them longer and harder to read by being too specific. Consider this name:

loggedInUserAuthenticatedByEmailAndPassword = …

This is way too specific! loggedInUser would suffice!

The key takeaways are:

  • Avoid comments that say the obvious or those which are misleading.
  • Never comment out code, just remove.
  • Use comments only when you want to provide licensing information, warnings or there is a need to provide API documentation.
  • Use comments when code is difficult to grasp at a single sight and it would make it easier by providing some comments as explanations (e.g: regex).
  • Properly format the code by adding blank lines to separate unrelated concepts and grouping similar/ related concepts together.
  • Do not write an unreadably long line of code or name in a single line. Split them into multiple lines and use precise short names.

I hope you found this article useful and put you into perspective about the style of coding you follow. Thanks for reading this and don’t forget to add your /*comments*/ for this post.

Join FAUN: Website 💻|Podcast 🎙️|Twitter 🐦|Facebook 👥|Instagram 📷|Facebook Group 🗣️|Linkedin Group 💬| Slack 📱|Cloud Native News 📰|More.

If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇

--

--