Use Meaningful Names in Your Code

Kavindu Wijesuriya | Sat Sep 11 2021
cleanCode
programming
bestPractices

We see user created names everywhere in our codebase. It's in our variables, functions, arguments, classes, and folders. "Clean Code: A Handbook of Agile Software Craftmanship by Robert C. Martin" quotes that "We name and name and name. Because we do so much of it, we'd better do it well". I couldn't have put those words any better.

Credits: Giphy.com

I have come across many code bases where I had to spend hours on, just to understand the code. It wasn't because the code itself was complex. As Robert C. Martin puts it, "The problem isn't the simplicity of the code but the implicity of the code".

A name of a variable or function should be able to answer the following questions:

  1. Why does it exist?
  2. What does it do?
  3. How is it used?

Example

Bad naming example

Consider the above snippet. If it wasn't for the comment we would have no idea what the variable `c` does. It does not tell us why it is there, what it stores or the purpose of it. To put it plainly - if a variable requires a comment, the name does not reveal its intent. Considering the above, let's rename our variable.

Good naming example

Okay! Now let's take a look at the following function. Measure how long it would take for you to understand what it does.

Bad function example

I bet it took at least a few minutes to understand what this function does. But I doubt you fully understood it. These are the questions that ring inside my mind when I go through it. 😕

  1. What kind of a list can I expect from the `getList` function?
  2. What does the `4` stand for in the `user.status` reference?

It is obvious that the `getList` function filters a set of users from the `users` object. But what kind of a filter? We wouldn't know for sure without deep diving into the code. Every single developer that comes across this code will have to take a deep dive into the user object to find out what this function is actually doing.

It is amazing how much of a difference that it makes by properly naming variables and functions. Check out the below example. I have only changed the names of the variables.

Good function naming example

Amazing right? It only takes a couple of seconds for someone to understand what the purpose of this function. This is the power of good naming.

perfect

I highly recommend that you read Clean Code by Robert C. Martin as it has helped me immensely to validate my coding practices and to be confident calling out any bad practices when reviewing other code.

built with from scratch by Kavindu Wijesuriya