Writing Clean Code

Overview

It is very important for every software developer to be able to write clean, understandable, and maintainable code. Writing clean code will not only be confusing to the user, but it can also confuse the author who is still in the process of writing the code. In my opinion, organization and neatness is the foundation of reaching success in anything. The two main components that will decide if your code is clean are the naming of variables and how functions are written. An article I read by Yiğit Kemal Erinç explained this well.

Naming Variables

We give variables names because they are far easier to remember than its memory address, which is a mixture of numbers and letters. Names give you more information about the variable as well. Someone using your code would likely have a tough time understanding a variable just by the memory address.

The name of a variable should be meaningful. If you need to attach a comment next to the variable to explain its purpose, then you need to rename the variable. The name should already tell you the variable’s purpose and why it exists, and how it should be used. If a name requires a comment, it does not reveal its intent. 

When naming variables, it’s important to avoid disinformation. For example, a variable that has the suffix “-list”  should be a linked list. For a variable to have the “-list” suffix and not be a linked list would be disinformation and lead to confusion.

Writing Functions

There are plenty of tips for how to design clean, easy-to-follow functions. One very helpful tip is to keep the functions small. Functions should be nowhere near 20 lines long. The longer a function gets, the more likely it is to do multiple things and have side effects. From the article, the most important concept was to make sure that your functions only do one thing. If your function only does one thing, it is guaranteed that your function will be small. A good way to check if your function is doing multiple things is if you can create another function out of it. As for side effects, unintended consequences of your code. Side effects can involve changing passed parameters and global variables, which will leave your code tangled up.

Conclusion

Clean coding is not a skill that you learn overnight. Like anything else you want to be good at, it takes practice and repetition. When you write code, make a habit of the clean code principles, so it becomes second nature.

Source

https://www.freecodecamp.org/news/clean-coding-for-beginners/

Design a site like this with WordPress.com
Get started