Clean Code Guidelines

 

1. Variable and Function names

1.1 Use intention-revealing names

Bad Code

const a = "Rahul";
const b = "Attuluri";
console.log(a);
console.log(b);
JAVASCRIPT

Clean Code

const firstName = "Rahul";
const lastName = "Attuluri";
console.log(firstName);
console.log(lastName);
JAVASCRIPT

1.2 Make your variable names easy to pronounce

Bad Code

let fName, lName;
let cntr;
let full = false;
if (cart.size > 100) {
full = true;
}
JAVASCRIPT

Clean Code

let firstName, lastName;
let counter;
const maxCartSize = 100;
const isFull = cart.size > maxCartSize;
JAVASCRIPT

2. Better Functions

2.1 Less arguments are better

Bad Code

function Circle(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
JAVASCRIPT

Clean Code

function Circle(center, radius) {
this.x = center.x;
this.y = center.y;
this.radius = radius;
}
JAVASCRIPT

2.2 Use Arrow Functions when they make code cleaner

Bad Code

const count = 0;
function incrementCount(num) {
return num + 1;
}
JAVASCRIPT

Clean Code

const count = 0;
const incrementCount = (num) => num + 1;
JAVASCRIPT

2.3 Use Async await for asynchronous code

Bad Code

myPromise
.then(() => {
return func1();
})
.then(() => {
return func2();
});
JAVASCRIPT

Clean Code

const doAllTasks = async () => {
await myPromise;
await func1();
await func2();
};
doAllTasks();
JAVASCRIPT

3. Comments

3.1 Noise comments are bad

Bad Code

/** The day of the month.
The week of a year.
*/
let dayOfMonth, weekOfYear;
JAVASCRIPT

3.2 If code is readable you don’t need comments

Bad Code

// Check to see if the employee is eligible for full benefits
if (employee.workingHours > 100 && employeeAge > 65){
isEligibleForFullBenefits();
}
JAVASCRIPT

Clean Code

if (employee.workingHours > 100 && employeeAge > 65){
isEligibleForFullBenefits();
}
JAVASCRIPT

4. Other code guidelines

  1. There are a lot more, that you can do to identify and avoid bad code.

  2. Below is a list of some code smells and anti-patterns to avoid.

4.1 Remove Dead code

Dead code is just as bad as duplicate code. There's no reason to keep it in your codebase. If it's not being called, get rid of it!

Bad Code

const x = 30;
const y = 25;
function myFunction() {
if (x > 18) {
console.log(x);
}
}
myFunction();
JAVASCRIPT

Clean Code

const x = 30;
function myFunction() {
if (x > 18) {
console.log(x);
}
}
myFunction();
JAVASCRIPT

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form