“Good programmers write code that humans can understand."- Martin Fowler
A crucial aspect that even the most experienced coders are required to keep in mind is how to write a clean code. Clean code can not only be read easily, but is also easier to maintain and debug. Usually, in a work setup, multiple people work on the same project so clean code practices make collaboration much easier. If we revisit already written code at a later point where some context is lost, writing clean code would make it extremely easy to regain context and work on the project once again. There are many aspects surrounding how to write clean code but we shall cover some pointers which beginners can work on.
Also Read | How Important Is It For Your Child To Learn To Code?
To begin with, a tip on how to write a clean code is to pick the right variable or function name which reveals the intention behind using or writing a certain piece of code is half the battle won. It could save a lot of effort in trying to decipher or recollect the rationale behind writing a certain piece of code later. This rule applies to names of package, class, variable, function, database tables, columns, property files, properties, everything. Even the name of the iterator variable in a for loop is equally important to keep code readable. Few things to keep in mind in this regard would be :-
Bad:
if (student.classes.length < 7) {
// Do something
}
Good:
if (student.classes.length < MAX_CLASSES_PER_STUDENT) {
// Do something
}
Here MAX_CLASSES_PER_STUDENT = 7 , which can be reused in some other class also , if required.
Some examples are printer.IsReady(), pen.CurrentColor(), etcetera.
One of the effective clean code tips is that functions should be precise and small. The longer a function gets, the chances are it is serving multiple purposes and thus increasing chances of errors. Smaller functions are easier to debug and refactor. One way to ensure the function is small is to see that it does only one thing. For instance, a function to retrieve a value and print the same can be broken down into functions, one to retrieve the value, and another one to print it.
if (shouldBeDeleted(timer))
is preferable to
if (timer.hasExpired() && !timer.isRecurrent()) .
Here shouldBeDeleted(timer) function encapsulates the logic mentioned in the second if statement
Boolean flag arguments counter the basis of single responsibility. When you look into them, you need to consider dividing the function into two. For example, if there is a function to book tickets and there are two types of customers, premium and non premium, instead of writing :
public Booking book (Customer aCustomer, boolean isPremium) {
if(isPremium)
// logic for premium book
else
// logic for regular booking
}
, you can prefer to write it as
isPremium(aCustomer) ? bookPremiumTickets(aCustomer ) : bookRegularTickets(aCustomer) ;
Do not repeat yourself in code. Code duplication might be the biggest issue while learning clean code practices. If you have two functions like follow :
public void ArchiveRecord()
{
Archived = true;
DateArchived = DateTime.Now;
}
public void CloseRecord()
{
Archived = true;
DateArchived = DateTime.Now;
}
, it would be wise to move the duplicated code to a shared method and avoid duplication. Duplication introduces errors, since if the logic was to change, you have to remember changing it at multiple places instead of a single function.
It would be hard to read books, if the line spacing or the font sizes were inconsistent on the same page. The same is for coding. Make sure the indentation, line breaks, and formatting are consistent. Make your code clear and easy to read with proper indentation, line breaks, and formatting. Braces and consistent indentation can help you easily see where the code blocks start and end. You can use IDE plugins for code formatting as well :-
VS Code: Prettier
Atom: Atom Beautify
Intellij : Code Formatter
Another clean code tip is that one should never leave code in comments, it is prudent to remove such comments as it is highly likely that the code will change over time, leaving the comment redundant and adding to confusion. It is also said that code should be self- documenting. Long comments that explain code or state the obvious can be avoided and better naming conventions or single responsibility principle can be used instead.
You need to know your language's conventions in context of spacing, comments, and naming things. There are various style guides available for various languages. For example, using camelCase in Java but snake_case in Python. These things change from one language to another and there are no universal standards.
Here are some useful links for you ( experienced software developers also follow these style guides ):-
This article has been written keeping in mind a novice to programming, and thus only suggestions that can be followed right from day one have been mentioned. We can delve deeper into practices around error handling, test driven development, concurrency etc, but those are slightly advanced topics which become relevant with more practice and experience. Having said that, these are just mere guidelines and not rules, and there is no one-size-fits-all solution. There is no one clear answer to how to write a clean code, but the experience of other developers and our own learning can go a long way in establishing clean code practices, thus enabling an ease of reading and troubleshooting code. For folks who are interested in reading and exploring further can refer to the following reading materials:-
Please remember that all these reading materials exist to provide insights into being a better developer and do not promote rules of any manner. At the end of the day, you should weigh the pros and cons of all such guidelines so that you are better convinced of why you are following a certain paradigm of writing code.
Also Watch | How Important Is It For You To Learn To Code?
Deboshree holds a BTech in Computer Science and Engineering from BIT Mesra. Backed with 6 years of experience working with Goldman Sachs and Walmart, she currently works with Cred as backend engineer.
Application Date:05 September,2024 - 25 November,2024
Application Date:15 October,2024 - 15 January,2025
Counselling Date:05 November,2024 - 08 November,2024