Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 30, 2023 09:40 am GMT

9 Must-Know Rules for Writing Clean Code

Are you tired of staring at a mess of code that even your cat wouldnt 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

Dont 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 togetherfunction calculateTotal() {  // code}function calculateTax() {  // code}function calculateDiscount() {  // code}// Use comments to explain the purpose of the codefunction 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 its been a while since you worked on the code.

Its 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 Im trying to say.

// Naming conventionslet userName; // camelCase for variables and propertiesconst MAX_USERS; // UpperCamelCase for constants// Commenting guidelines// This function takes in a number and returns its squarefunction square(num) {   return num * num;}

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

Rule#3 - Use descriptive variable and function names

I know its stylish to name your variables X and Y.

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

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

// Descriptive function namefunction 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 functions 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, youll be able to store values that you know wont 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 off as a developer, its 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 doesnt.

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 wont 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, its 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.

Heres 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 orderconst shoppingList = ["milk", "bread", "eggs"];console.log(shoppingList[1]); // Output: "bread"// Using a list to store a collection of items that can change dynamicallyconst 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 keyconst 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, youll 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 isnt committed to a central repository.

Every developer should get used to version control. Dont 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

Dont 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 Gulpconst gulp = require('gulp');gulp.task('build', function() {// Build process logic});gulp.task('default', ['build']);

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

Dont be a dinosaur. Youre only going to go extinct.

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

For example, if youre 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

Thats 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, youll 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


Original Link: https://dev.to/dashsaurabh/9-must-know-rules-for-writing-clean-code-1kp1

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To