A Beginner’s Guide To Clean Coding

A Beginner’s Guide To Clean Coding

Edited By Team Careers360 | Updated on Nov 07, 2024 05:42 PM IST

“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.

A Beginner’s Guide To Clean Coding
A Beginner’s Guide To Clean Coding

Also Read | How Important Is It For Your Child To Learn To Code?

Naming Variables

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 :-

  • Do not use letters like x, y, a, or b as variable names. Sooner or later, they become extremely confusing to understand as to why they were used in the first place.

  • For following clean code practices, do not use abbreviations, but instead use descriptive names, for example, totVal can be expanded to totalValue

  • Use variables for constants instead of using them straight away. It facilitates reusability of the variable and also makes them searchable. For example :

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.

  • Following the one word for each concept rule is a must. You should not use fetch, retrieve, and get for doing the same operation in different classes. You should choose one of them and use it throughout the project so people who maintain the codebase can find what they are looking for. For instance, if there are methods to print values of something in the code, you can always begin the method name by ‘print’ , so that you can understand the intention or search for it easily. For someone new to the codebase, this practice makes it a self-documenting code and they can go through it with ease.

  • One of the good clean code practices is that if the names are too long to establish the intent of the usage, it might be time to break down the function into smaller functions so that you can describe the intention smoothly in the name. Bear in mind that long names aren’t the problem, the routine/code might be.

  • For functions, try using a description of the return value. This is an easy, straightforward rule.

Some examples are printer.IsReady(), pen.CurrentColor(), etcetera.

code cleaning, clean code tips, clean code architecture, cleancoders, code cleaners, clean code naming, how to write clean code, how to write a clean code, write clean code, clean code practicesA 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

Establishing Code Quality Through Functions

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.

  1. Sometimes if a function contains some logic in if-else, it could be moved to another function, thus making the code cleaner. For example:

if (shouldBeDeleted(timer))
is preferable to

if (timer.hasExpired() && !timer.isRecurrent()) .
Here shouldBeDeleted(timer) function encapsulates the logic mentioned in the second if statement

  1. 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) ;

  1. 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.

Consistent Formatting And Indentation

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

Avoid Unnecessary Comments

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.

Know Your Language's Conventions

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 ):-

  • Python Style Guide
  • Google’s Javascript Style Guide
  • Google Java Style Guide

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:-

  • Clean Code: A Handbook of Agile Software Craftsmanship By Robert C. Martin
  • The Pragmatic Programmer by Hunt Andrew, Thomas David
  • Code Complete by Steve Mcconnell

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.

Get answers from students and experts
Back to top