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;
}
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;
}
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;
}
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);
}
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 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;
}
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"
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"
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");
}
});
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']);
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
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.
If you liked this post, do subscribe to the newsletter for regular updates.
You can also connect with me on other platforms: