Scroll to top

Clean code strategies to be better programmer


Madhav Poudel - July 10, 2019 - 0 comments

If you are a programmer of two or more years of experience then, you might have felt daunting working on legacy code. The productivity of a team in a project decreases with the increasing span of time. This is due to the fact that new features need to be added on the code base, each features added tantamount to leaving room for the feature to append in future. As a result, the code gets messy and time to maintain the project staggeringly increases. After a long run of the process, the software gets old and need to be rebuilt in new technology with a strong team. All the features of the old system need to be implemented on the new one while the old system still being exposed to the user and upgraded based on feedback. The race of two team building and maintaining the same system continues until the new system is equivalent to the recent old system. It not only slows down the project but also costs huge expenses to the company. Moreover, Working on a legacy system decreases productivity and directly hampers their expectation to learn new tools in the market.

However, This can all be prevented if clean code strategies are followed from the beginning of the project. Simply we can define Clean Code as code that is easy to understand and change in the future. The primary goal of clean code is to self-document the code so that it becomes easier for developers who work on the same codebase in the future by keeping the code simple and preventing from a misunderstanding of the system. 

In the article, we will look at some of the strategies we can start implementing to keep our code simple and clean. Moreover, the comparison between bad and good code helps you to get insights quickly on these strategies.

Naming

Names are everywhere in code like variables name, functions name, classes name, packages name, files name and so on. we can thus say that naming exhibit a significant portion of our development work. It is important that we choose a meaningful name with certain conventions.

Use Meaningful and Pronounceable Name

// ❌ Bad Code
const ddmmyyyy = moment().format("DD/MM/YYYY"); 

// ✔️ Good Code
const currentDate = moment().format("DD/MM/YYYY"); 

The name currentDate is meaningful and pronounceable than ddmmyyyy. It keeps the clean code and let us know what the moment date object is referring to.

Use searchable Names

// ❌ Bad Code
if (userAccounts.length > 5) {
  sendEmail(userAccounts.email);
}

// ✔️ Good Code
const MIN_ACCOUNTS = 5;
if (userAccounts.length > MIN_ACCOUNTS) {
  sendEmail(userAccounts.email);
}

In the first case, It becomes difficult to understand the conditional statement as it is difficult to know what 5 means. To make it understand, it is good practice to give the constant a self explaining name. It not only makes the code clean but also make it reusable in another code block.

Use Self Explaining Variable

// ❌ Bad Code
const gtUsrAcc = async () => {
  const urs = await database.find('userAccounts');

  return urs;
}

// ✔️ Good Code
const getUserAccounts = async () => {
  const userAccounts = await database.find('userAccounts');

  return userAccounts;
}

In Bad Code, the variable gtUsrAcc and urs don’t give us insights on what is happening inside code at the first look. It is good practice to use the variable name which explains what is does by its name. Remember that long name is not a problem because we are already benefited by code editor which autocompletes our variable name while using elsewhere.

Constistent Naming Conventions

// ❌ Bad Code
getUserInfo();
retrievePostData();
fetchAccountInfo();

// ✔️ Good Code
getUserInfo();
getPostInfo();
getAccountInfo();

Consistent naming is what keeps us from misunderstanding code and keeps the code clean. In the first case, get, retrieve and fetch means the same and using this variation in the name makes it difficult to read code. so, It is important to keep the naming conventions consistent throughout the code.

Functions

The main notion about function is to keep it small and to make sure it does one and only one thing. It should be built in such a way that it is easily testable. Furthermore, practicing Test Driven Development enforces developer to build a simple and testable function from the start of the project.

Function should do one thing

// ❌ Bad Code
const newUser = { email, password };
const registerUser = async (newPost) => {
  const user = database.users.findUserByEmail(newPost.email);
  if(user) {
    return;
  }
  await database.createPost(newPost)
}

// ✔️ Good Code
const newUser = { email, password };

const userAlreadyExists = email => {
  const user = await database.users.findUserByEmail(email);
  if(user) {
    return true;
  }
  return false;
}

const registerUser = async (newPost) => {
  if(!userAlreadyExists(newPost.email)) {
    await database.createPost(newPost)
  }
}

By keeping the function simple, It not only makes it easy to test but also clearly explains what it does without get bogged down inside huge code.

Use few arguments (not more than two)

// ❌ Bad Code
const createPost = async (title, description, excerpt, author) => {
  const newPost = { title, description, excerpt, author };
  await database.createPost(newPost)
}

// ✔️ Good Code
const createPost = async ({ title, description, excerpt, author }) => {
  const newPost = { title, description, excerpt, author };
  await database.createPost(newPost)
}

// ✔️✔️ Even Better Code
const newPost = { title, description, excerpt, author };
const createPost = async (newPost) => {
  await database.createPost(newPost)
}

Using a few arguments makes it easier to test the function. Having many arguments enforce to test argument with different cases with seperate arguments. It is common practice to use an object instead of many arguments in a language like Javascript.

Write Good Function

Additionally, You can write good function by using the clear name about what it does (generally verbs), removing duplication of same code, avoiding boolean as arguments in function.

Comments

Most programmers think that they should write comments in their code to make it professional. Actually, Comments are excuses for writing bad code. If the code is good enough then, comments are not necessary. Previously we talked about naming variables and functions. If the name has the meaning of what it does then, It is not necessary to write a comment. Moreover, It becomes a redundancy of information in code.

Comment only when necessary

// ❌ Bad Code
// The current date
const currentDate = moment().format("DD/MM/YYYY");

// ✔️ Good Code
const currentDate = moment().format("DD/MM/YYYY");

// ❌ Bad Code
// Get users from database
const getUsers = async () => {
  const users = await database.find('users');
  return users;
};

// ✔️ Good Code
const getUsers = async () => {
  const users = await database.find('users');
  return users;
};

You are supposed to comment only when it is necessary to explain particular information. Otherwise, you should explain information through the code.

Don’t leave commented code in your codebase

// ❌ Bad Code
getUsers();
// getUniqueUsers();
// getPosts();

// ✔️ Good Code
getUsers();

Leaving out commented code in the codebase confuses developer whether it should be kept or removed. Code gets messy over time because of this bad practice.

TODO Comments

getUsers();
// TODO: send email to all users

TODO comments are generally used to remind developer about the pending work to do on a particular file. Modern code editors make it easier to browse such comments so it is unusual to these TODO gets unnoticed. It is best practice to use keywords TODO, so that comment doesn’t get left behind in the codebase and the problem gets solve at some point.

Code Formatting

It is said that, While we write code, We do more back and forth searching for information in code than actually write the code. The code we write should be formatted in a consistent manner so that it looks clean and most importantly easy for us to find the required information. Code Formatting is actually time-consuming process and takes time for us to be comfortable. Fortunately, there are linter tools in almost all programming language nowadays which does the auto-formatting in our code editor. For example, eslint is used in Javascript language. By configuring the eslint in our project through our code editor and linking lint rules like Airbnb eslint rules, it is easy to make our hands dirty on it.

So, we looked at some of the best strategies to practice writing clean code. Writing clean code not only makes us professional at what we do but also shows responsibility to the code for further improvement in the future.

Post a Comment

Your email address will not be published. Required fields are marked *