Clean code makes your code easier to understand

Introduction to the

If you care not only about how your code works, but also how well your code is written, then you’re pursuing clean code.

_ Professional developers will write code for their future selves and “others,” not just machines

Based on the above discussion, clean code is defined as writing code in a way that is self-explanatory, easy to understand, and easy to modify and extend.

Even bad code can work, but sloppy code can be a real headache for development teams.

This article introduces code cleanliness in Javascript, but it can be applied to other programming languages as well.

1. Strong type checking

Use === instead of ==

0 == false // true 
0 === false // false 
2 == "2" // true 
2 === "2" // false 

// example 
const val = "123"; 
if (val === 123) { 
  console.log(val); 
  // it cannot not be reached 
} 
if (val === "123") { 
  console.log(val); 
  // it can be reached
}
Copy the code

2. Name variables

Name your variables in a way that expresses their intended use

In this way, these variables can be made searchable and make them highly readable.

Don’t recommend ๐Ÿ‘Ž

let daysSLV = 10;

let y = new Date().getFullYear();

let ok;

if (user.age > 30) {
  ok = true;
}
Copy the code

Recommend ๐Ÿ‘

const MAX_AGE = 30; let daysSinceLastVisit = 10; let currentYear = new Date().getFullYear(); . const isUserOlderThanAllowed = user.age > MAX_AGE;Copy the code

Don’t add extra and unnecessary words to your variable names.

Don’t recommend ๐Ÿ‘Ž

let nameValue;

let theProduct;
Copy the code

Recommend ๐Ÿ‘

let name; 

let product;
Copy the code

Don’t ignore the need to store context information for variables

Don’t recommend ๐Ÿ‘Ž

const products = ["T-Shirt", "Shoes", "Watches", "Bags"]; products.forEach(p => { doSomething(); doSomethingElse(); / /... / /... / /... / /... // what does' p 'mean? register(p); });Copy the code

Recommend ๐Ÿ‘

const products = ["T-Shirt", "Shoes", "Watches", "Bags"];

products.forEach(product => {
  doSomething();
  doSomethingElse();
  // ...
  // ...
  // ...
  register(product);
});
Copy the code

Don’t add unnecessary information to variables

Don’t recommend ๐Ÿ‘Ž

Const product = {productId: 1, productName: "T-shirt ", productPrice: 8.99, productUnits: 12}; . product.productName;Copy the code

Recommend ๐Ÿ‘

Const product = {id: 1, name: "T-shirt ", price: 8.99, units: 12}; . product.name;Copy the code

Use the same vocabulary for variables of the same type

Don’t recommend ๐Ÿ‘Ž

getUserInfo();

getClientData();

getCustomerRecord();
Copy the code

Recommend ๐Ÿ‘

getProduct();
Copy the code

3. The function

Use descriptive function names.

Since a function usually represents a specific behavior, the function name should take a verb or phrase that adequately conveys the intent behind the function and the meaning of its parameters.

The function name is what the function does

Don’t recommend ๐Ÿ‘Ž

function email(user) { 
  // implementation 
}
Copy the code

Recommend ๐Ÿ‘

function sendEmailUser(emailAddress) { 
  // implementation 
}
Copy the code

Avoid too many parameters

Ideally, a function should have two or fewer arguments. The smaller the number of arguments, the easier the function is to test

Don’t recommend ๐Ÿ‘Ž

function getProducts(fields, fromDate, toDate) { 
  // implementation 
}
Copy the code

Recommend ๐Ÿ‘

function getProducts({ fields, fromDate, toDate }) {
  // implementation
}

getProducts({
  fields: ['id', 'name', 'price', 'units],
  fromDate: '2020-07-01',
  toDate: '2020-07-22'
});
Copy the code

Use default parameters instead of conditional judgments

Don’t recommend ๐Ÿ‘Ž

function createShape(type) { 
  const shapeType = type || "circle"; 
  // ... 
}
Copy the code

Recommend ๐Ÿ‘

function createShape(type = "circle") { 
  // ... 
}
Copy the code

Avoid performing multiple operations in a function body

Don’t recommend ๐Ÿ‘Ž

function notifyUsers(users) { users.forEach(user => { const userRecord = database.lookup(user); if (userRecord.isVerified()) { notify(user); }}); }Copy the code

Recommend ๐Ÿ‘

function notifyVerifiedUsers(users) {
  users.filter(isUserVerified).forEach(notify);
}

function isUserVerified(user) {
  const userRecord = database.lookup(user);
  return userRecord.isVerified();
}
Copy the code

Use object. assign to set the default Object

Don’t recommend ๐Ÿ‘Ž

const shapeConfig = {
  type: "circle",
  width: 150,
  height: null
};

function createShape(config) {
  config.type = config.type || "circle";
  config.width = config.width || 300;
  config.height = config.height || 300;
}

createShape(shapeConfig);
Copy the code

Recommend ๐Ÿ‘

const shapeConfig = { type: "circle", width: 150 // Exclude the 'height' key }; function createShape(config) { config = Object.assign( { type: "circle", width: 300, height: 300 }, config ); . } createShape(shapeConfig);Copy the code

Do not use flag bits as arguments, as this makes the function more useful than it is supposed to be

Don’t recommend ๐Ÿ‘Ž

function createFile(name, isPublic) { if (isPublic) { fs.create(`./public/${name}`); } else { fs.create(name); }}Copy the code

Recommend ๐Ÿ‘

function createFile(name) {
  fs.create(name);
}

function createPublicFile(name) {
  createFile(`./public/${name}`);
}
Copy the code

Do not pollute global variables

If you want to extend existing objects, use ES6’s Class classes and inheritance syntax instead of creating extension functions on the prototype chain of native objects.

Don’t recommend ๐Ÿ‘Ž

Array.prototype.myFunction = function myFunction() { 
  // implementation 
};
Copy the code

Recommend ๐Ÿ‘

class SuperArray extends Array { 
  myFunc() { 
    // implementation 
  } 
}
Copy the code

4. Conditional judgment

Avoid negative conditions (which complicate logic)

Don’t recommend ๐Ÿ‘Ž

function isPostNotPublished(post) { // implementation } if (! isPostNotPublished(post)) { // implementation }Copy the code

Recommend ๐Ÿ‘

function isPostPublished(user) {  
  // implementation
}

if (isPostPublished(user)) {  
  // implementation
}
Copy the code

Use simplified conditional judgments

This rule may seem trivial, but it’s worth mentioning. Use this rule to make code more concise when it is clear that a value is not undefined or NULL, and when the value is of Boolean type.

Don’t recommend ๐Ÿ‘Ž

if (isValid === true) { 
  // do something... 
} 

if (isValid === false) { 
  // do something... 
}
Copy the code

Recommend ๐Ÿ‘

if (isValid) { // do something... } if (! isValid) { // do something... }Copy the code

Avoid using conditional judgments under any circumstances

Using polymorphism and inheritance

Don’t recommend ๐Ÿ‘Ž

class Dog { // ... getBreed() { switch (this.type) { case "GermanShepherd": return this.getStandardSize("GermanShepherd"); case "JackRussellTerrier": return this.getStandardSize("JackRussellTerrier"); case "ShibaInu": return this.getStandardSize("ShibaInu"); }}}Copy the code

Recommend ๐Ÿ‘

class Dog { // ... } class GermanShepherd extends Dog { // ... getStandardSize() { return this.standardSize; } } class JackRussellTerrier extends Dog { // ... getSize() { return this.standardSize; } } class ShibaInu extends Dog { // ... getSize() { return this.standardSize; }}Copy the code

5. ES Classes

The class syntax is the new syntactic sugar of Javascript. In addition to being written differently, the Class syntax achieves the same effect as using prototypes and makes the code much simpler.

Don’t recommend ๐Ÿ‘Ž

const Product = function(name) { if (! (this instanceof Product)) { throw new Error("Instantiate Product with `new` keyword"); } this.name = name; }; Product.prototype.getSize = function getSize() { /**/ }; const Tshirt = function(name, color) { if (! (this instanceof Tshirt)) { throw new Error("Instantiate Tshirt with `new` keyword"); } Product.call(this, name); this.color = color; }; Tshirt.prototype = Object.create(Product.prototype); Tshirt.prototype.constructor = Tshirt; Tshirt.prototype.printColor = function printColor() { /**/ };Copy the code

Recommend ๐Ÿ‘

class Product { constructor(name) { this.name = name; } getDiscount() { /* ... */ } } class Tshirt extends Product { constructor(name, color) { super(name); this.color = color; } getSize() { /* ... * /}}Copy the code

Use the chain method

Many popular libraries, such as jQuery and Lodash, use this pattern, which makes code less verbose.

By returning this at the end of each function in the class you define, you can chain in more class functions later.

Don’t recommend ๐Ÿ‘Ž

class Product { constructor(name) { this.name = name; } setPrice(price) { this.price = price; } setUnits(units) { this.units = units; } save() { console.log(this.name, this.price, this.units); } } const product = new Product("Bag"); Person. SetPrice (23.99); person.setUnits(12); person.save();Copy the code

Recommend ๐Ÿ‘

class Product { constructor(name) { this.name = name; } setName(name) { this.name = name; // Return this for chaining return this; } setPrice(price) { this.price = price; // Return this for chaining return this; } save() { console.log(this.name, this.price, this.units); // Return this for chaining return this; }} const product = new product (" T-shirt ").setname ("Jeans").setage (31.99).save();Copy the code

6. Avoid eval

The eval function can pass a string to the Javascript compiler and execute it as a Javascript statement

In short, anything you pass around at run time will be executed just as it was added at design time.

eval("alert('Hi');" );Copy the code

The above code will pop up a message box with “Hi” when executed

The Eval function should be avoided as much as possible because it is not secure and provides a potentially threatening vehicle for malicious programmers.

7. Use JSLint

A code format verification tool such as JSLint is a great aid in writing canonical code. The use of such tools will be discussed later.

8. Overall pit avoidance

Do not duplicate your work as much as possible, and avoid unused code and dead code. [It is recommended to delete it directly]

conclusion

This is just a small part of the code you can improve. I think the principle in question is one that people often don’t follow. They did their best, but it was not easy to maintain the strength of mind and consistently perform well. Maybe at the beginning of the project, the code

It’s neat, but before the deadline, principles are often ignored and moved to the “TODO” or “REFACTOR” section.

medium.com/javascript-…