DEV Community

Cover image for 9 Must-Know Rules for Writing Clean Code
Saurabh Dashora
Saurabh Dashora

Posted on

9 Must-Know Rules for Writing Clean Code

Are you tired of staring at a mess of code that even your cat wouldn’t touch?

Look no further. In this post, I will tell you 9 rules to turn your spaghetti code into a work of art.

So grab a cup of coffee, sit back and take charge of your code!

Rule#1 - Keep your code organized and easy to read

Don’t organize your wardrobe but definitely organize your code. By keeping your code organized and easy to read, you can find what you need in a snap.

Check the below example:

// Group related functions together
function calculateTotal() {
  // code
}

function calculateTax() {
  // code
}

function calculateDiscount() {
  // code
}

// Use comments to explain the purpose of the code
function calculateTotal() {
  // calculate subtotal
  let subtotal = 0;
  // add items
  subtotal += item1.price;
  subtotal += item2.price;
  // return total
  return subtotal;
}
Enter fullscreen mode Exit fullscreen mode

As you can see, a little bit of planning and a healthy dose of comments can make it a breeze to navigate your code.

At one glance, you get a good idea of the overall functionality even after it’s been a while since you worked on the code.

It’s not every day that you thank your past self for doing something good!

Rule#2 - Follow Established Coding Conventions and Standards

I know it is tempting to be a rebel and chart your own course.

But sometimes, it pays to follow established coding conventions and standards. This includes things like naming conventions, commenting guidelines and more.

See the below snippet for what I’m trying to say.

// Naming conventions
let userName; // camelCase for variables and properties
const MAX_USERS; // UpperCamelCase for constants

// Commenting guidelines
// This function takes in a number and returns its square
function square(num) { 
  return num * num;
}
Enter fullscreen mode Exit fullscreen mode

The idea is to play the game with consistency. By following the code conventions of your team, your code won’t stick out like a sore thumb and your fellow developers will appreciate you.

Rule#3 - Use descriptive variable and function names

I know it’s stylish to name your variables X and Y.

But trust me, even you won’t be able to understand their true meaning after a few months.

It’s always safe to give descriptive names to variables. It might even be better for you in the long run.

// Descriptive function name
function calculateSum(numbers) {
  // Descriptive variable name
  let sum = 0;
  // Iterate through the array of numbers
  for (let i = 0; i < numbers.length; i++) {
    // Add each number to the sum
    sum += numbers[i];
  }
  // Return the sum
  return sum;
}
Enter fullscreen mode Exit fullscreen mode

As you can see, even if the function’s code has a loop, the function and variable name makes the objective of the program absolutely clear.

Rule#4 - Avoid Hard-Coding Values and Use Constants

Say goodbye to hard coding and hello to constants!

By using constants, you’ll be able to store values that you know won’t change throughout your program. This will help you avoid the headache of having to search and replace values throughout your code.

Check out the below code.

const TAX_RATE = 0.07;

function calculateTotal(subtotal) {
  return subtotal + (subtotal * TAX_RATE);
}
Enter fullscreen mode Exit fullscreen mode

If the tax rate changes in the future, you can easily update the value in one single place and have it reflected throughout your code.

Rule#5 - Keep functions small and focused

When you are starting off as a developer, it’s always tempting to turn your functions into swiss knives. The feeling of explaining that your code can do so much stuff is so enticing.

As you become a seasoned developer, this habit wears off. But sometimes it doesn’t.

Trust me on this. Keep your functions small and your life will be happy.

If you write small and focused functions that are easy to understand, chances are that you won’t be disturbed on your beach vacation if something goes wrong.

See this example.

function calculateTotal(subtotal, tax, discount) {
  const total = subtotal + tax - discount;
  return total;
}
Enter fullscreen mode Exit fullscreen mode

The above function is short and to the point. This makes it easy to understand and maintain.

Rule#6 - Use Appropriate Data Structures

Are you always trying to fit a square peg in a round hole? If yes, it’s time to use appropriate data structures.

Just like a carpenter has a variety of tools for different tasks, a developer should have a variety of data structures for different types of functionality.

Here’s a cheat sheet:

  • Use arrays when you need to store a collection of items that have a specific order.
  • Use lists when you need to store a collection of items that can change dynamically.
  • Lastly, use maps if you need to store a collection of items that can be accessed by a key.

Check out the below code that demonstrates the use of different data structures.

// Using an array to store a collection of items that have a specific order
const shoppingList = ["milk", "bread", "eggs"];
console.log(shoppingList[1]); // Output: "bread"

// Using a list to store a collection of items that can change dynamically
const todoList = ["write code", "debug", "test"];
todoList.push("deploy");
console.log(todoList); // Output: ["write code", "debug", "test", "deploy"]

// Using a dictionary to store a collection of items that can be accessed by a key
const phonebook = {
  "John": "555-555-5555",
  "Mary": "555-555-5556",
  "Bob": "555-555-5557"
};
console.log(phonebook["Mary"]); // Output: "555-555-5556"
Enter fullscreen mode Exit fullscreen mode

By using an appropriate data structure based on the requirement, you’ll find that your code is not only efficient but also easy to understand.

Rule#7 - Use Version Control

Just like your application is useless if it only runs on your machine, your code is useless if it isn’t committed to a central repository.

Every developer should get used to version control. Don’t forget to commit your code regularly. If you are doing it, make sure others on your team also do it.

All it takes is a few commands:

// Initialize a new Git repository
$ git init

// Add all files to the repository
$ git add .

// Commit the changes with a message
$ git commit -m "Initial commit"
Enter fullscreen mode Exit fullscreen mode

A good version control tool allows developers to track changes, collaborate with others and easily revert to previous versions in case of any issues.

Rule# 8 - Automate Repetitive Tasks

Don’t be like a hamster on a wheel, constantly running in circles and doing the same boring tasks over and over again.

You should use tools and scripts to automate repetitive tasks in your code. This will not only save time but also make your code more reliable and efficient.

Check out this code example of a simple testing automation script.

const testCases = [
    { input: [1, 2], expectedOutput: 3 },
    { input: [2, 3], expectedOutput: 5 },
    { input: [3, 4], expectedOutput: 7 },
];

testCases.forEach(testCase => {
    const output = addNumbers(testCase.input[0], testCase.input[1]);
    if (output !== testCase.expectedOutput) {
        console.error(`Test failed: expected ${testCase.expectedOutput} but got ${output}`);
    } else {
        console.log("Test passed");
    }
});
Enter fullscreen mode Exit fullscreen mode

You can also automate the building process for compiling your code and creating a final package.

See the below example where we automate a build process using a tool like Gulp.

// Automating a build process using a tool like Grunt or Gulp
const gulp = require('gulp');

gulp.task('build', function() {
// Build process logic
});

gulp.task('default', ['build']);
Enter fullscreen mode Exit fullscreen mode

Rule#9 - Keep your code up-to-date

Don’t be a dinosaur. You’re only going to go extinct.

Keep your code up-to-date. Update your application dependencies whenever possible.

For example, if you’re working in the Node ecosystem, keep the NPM up-to-date and upgrade your development environment.

// Keep dependencies up-to-date using package manager
$ npm update

// Keep the development environment up-to-date
$ nvm install 12.16.3
Enter fullscreen mode Exit fullscreen mode

That’s it!

Well, there you have it. 9 rules to help you write clean and efficient code.

Of course, these are not the only things that matter. But by following them, you’ll be able to start on the path to writing code that not only works well but also appears pleasing for others to read, understand and maintain.

And if you have any other rules, do mention them in the comments section below.

You can also connect with me on other platforms:

My Regular Newsletter

Twitter

LinkedIn

Youtube

Top comments (19)

Collapse
 
fasaas profile image
fasaas • Edited

One quick reflection, if you need to write comments it means the code is not self explanatory. You should avoid writing comments because it means the code takes more to read and also comments can fall out of sync. The code should be the sole documentation of the logic.

Collapse
 
pilcrowonpaper profile image
pilcrowOnPaper • Edited

Self documenting code is a lie. Documentation isn't just about explaining what the code does, it's for explaining the "why" part as well. Why is this code needed, why is this implementation better than other solutions?

Also, if you're implementing an algorithm, it's usually a good idea to comment the algorithm name, links how it works, and maybe some quick notes on it.

Collapse
 
dashsaurabh profile image
Saurabh Dashora

A really valid point! Documentation can be utilized in quite useful ways.

Collapse
 
tinussmit profile image
Tinus Smit

I agree. The mere fact that there's nothing compelling the developer to update the comment when the code changes means it will mostly go out of sync as time and developers move on. This doesn't mean there should be no comments at all. But I treat commenting more like an apology. Allow me to explain...

An apology for:

  • A specific hack / workaround that needed to be implemented.
  • A complex piece that's hard to break down into smaller parts.
  • Potential side-effects that might occur when changing this bit of code.

Notice how all of the reasons are around less-than-ideal bits of code? One doesn't always have the luxury of starting from a clean slate, and even more often you're extending someone else's legacy code. Often times you also don't have the time available to "fix it properly", so you have to make do with what you have.

Collapse
 
dashsaurabh profile image
Saurabh Dashora

Hi Tinus, A really nice perspective on the debate about code commenting...thanks for bringing it up

Collapse
 
luisferfranco profile image
Luis F. Franco

As with almost anything... it depends. In most cases I completely agree with you, but sometimes business logic is so complex (maybe "strange" would be a better word than complex) that you NEED to add comments

Collapse
 
dashsaurabh profile image
Saurabh Dashora

Yes...i have also found that to be the case many times..."strange" is the right word and that's when I feel a quick comment can add a lot of value...

Collapse
 
siwhelan profile image
Simon Whelan

What you may think is ‘self-explanatory’ might make no sense at all to someone else. Comments allow more seamless work between groups.

Collapse
 
thexdev profile image
M. Akbar Nugroho

It's remind me 3 years ago. Even when you think it's "self-explanatory", but after one years, I believe you can't understand what the codes mean.

Collapse
 
dashsaurabh profile image
Saurabh Dashora

yes...i have seen that type of code...made perfect sense to the one who wrote it...but not so much to the others

Collapse
 
dashsaurabh profile image
Saurabh Dashora

I believe sometimes it is also a matter of following the conventions of the team or product...but yes, if you are getting a chance to start a blank-slate project, it's better to avoid comments

Collapse
 
syeo66 profile image
Red Ochsenbein (he/him)

I think no and redundant comments are bad. Write readable code and add comments about why the code exists when needed.

Thread Thread
 
dashsaurabh profile image
Saurabh Dashora

Nice point...adding comments should be the last resort unless your job is on the line bcz of some sort of team culture that i have seen in certain orgs :)

Collapse
 
pierrewahlberg profile image
Pierre Vahlberg • Edited

Another reeeeelly strong point for enums/constants instead of harscoded values is how well it reads. This together with pure functions is a huge win. Compare these examples (and notice how comments arent needed.. 😏)

// poor
const total = cartItems.map( p => p.price × 1.25);

// better
const taxRateFactorial = 1.25;
const cartTotal = cartItems.map( product => product.price × taxRateFactorial);

// More readable option

// clear constant name intent
const TAX_RATE = 0.25;

// use of pure functions
function getTaxesForPrice( price: number) {
  return price × TAX_RATE;
}
function addTaxesToPrice( price: number) {
   return price + getTaxesForPrice(price);
}
function getProductPrice(product) {
    return product.price;
}

// actual logic reads well and is easy to follow without comments

const products = cartItems; 
const prices = products.map(getProductPrice);

const totalIncludingTaxes = prices.map(addTaxesToPrice);

Enter fullscreen mode Exit fullscreen mode
Collapse
 
mickmelon profile image
MickMelon

Nice article. I couldn't agree more about the important of writing clean code. It goes a long way in making the code easier to understand and maintain, even when you are the only one working on the project.

I'd also add that consistency is better than correctness. If you are coming onto a well-established project, then you should follow the existing code styles and conventions, even if there are no specific guidelines. If every developer follows their own preferred coding style, then it could quickly lead to confusion and reduce overall code quality.

Collapse
 
dashsaurabh profile image
Saurabh Dashora

Absolutely agree with your point! Following project conventions is very important. Changes, if needed, should be brought in over time with a proper agreement...

Collapse
 
arsalannury profile image
ArsalanNury

hi 😊👋 thanks for sharing this great article.

Collapse
 
jhelberg profile image
Joost Helberg

Grouping (#1) should be based upon abstraction level. Further, code is a byproduct of the documentation (what why, how), see literate programming.

Collapse
 
harryrefact profile image
Makarov

There are tools that help you write good, unique code. Use AppRefactoring or Sourcery AI