Some tips to make your code elegant

Why write elegant code?

Use concise syntax and structure, follow consistent naming conventions, have good code organization and comments, and express the intent and logic of the code.

It mainly has the following advantages:
  • Readability: Easy to read and understand. Clear naming, concise syntax and good code structure can make the intention of the code clearer, reduce the difficulty of understanding the code, and improve the readability of the code.
  • Maintainability: Easy to maintain. When the code logic is clear and the structure is concise, developers can locate and fix bugs more quickly, and expand or modify functions. At the same time, highly readable code also facilitates subsequent code refactoring and optimization.
  • Scalability: More scalable and flexible. Clear code structure and concise coding style make it easier to add new features, modify existing features, or extend the code. In addition, concise code tends to rely less on specific implementation details, providing more flexibility and replaceability.
  • Error reduction and debugging time: It is easier to write correct logic, reducing the chance of errors. At the same time, when a problem occurs with the code, elegant and concise code makes it easier to debug and locate errors.
  • Performance optimization: Concise code is usually more efficient, reducing unnecessary calculation and resource consumption. Streamlined code structure and algorithms can improve code execution efficiency and performance.
1. Use arrow functions to simplify function definitions

Arrow functions are a syntax introduced in ES6 that can shorten the code length of functions while improving the readability of the code.

// 传统函数定义
function add(a, b) {
 return a + b;
 }
// 箭头函数简化
const add = (a, b) => a + b;
2. Use destructuring assignment to simplify variable declaration

Destructuring assignment is a syntax introduced in ES6, which can destructure the values ​​​​in an object or array and assign them to variables. This can make the code more concise and easy to understand, and improve the readability and maintainability of the code.

// 传统变量声明
const firstName = person.firstName;
const lastName = person.lastName;
// 解构赋值简化
const { firstName, lastName } = person;
3. Use template literals for string concatenation

Before ES6, we usually used the plus sign or concat() method to concatenate strings. However, this method is more cumbersome and the code is less readable. In ES6, we can use template strings to handle string concatenation, which can make the code clearer and easier to understand.

// 传统字符串拼接
const greeting = 'Hello, ' + name + '!';
// 模板字面量简化
const greeting = `Hello, ${name}!`;
4. Use the spread operator for array and object operations
// 合并数组
const combined = [...array1, ...array2];
// 复制对象
const clone = { ...original };
5. Use higher-order methods of arrays to simplify loops and data operations
// 遍历数组并返回新数组
const doubled = numbers.map(num => num * 2);
// 过滤数组
const evens = numbers.filter(num => num % 2 === 0);
6. Use conditional operators to simplify conditional judgments
// 传统条件判断
let message;
if (isSuccess) {
 message = 'Operation successful';
} else {
 message = 'Operation failed';
}
// 条件运算符简化
const message = isSuccess ? 'Operation successful' : 'Operation failed';
7. Use object destructuring and default parameters to simplify function parameters
// 传统参数设置默认值
function greet(name) {
 const finalName = name || 'Guest';
 console.log(`Hello, ${finalName}!`);
 }
// 对象解构和默认参数简化
function greet({ name = 'Guest' }) {
 console.log(`Hello, ${name}!`);
}
8. Use functional programming concepts such as pure functions and function composition
// 纯函数
function add(a, b) {
 return a + b;
 }
// 函数组合
const multiplyByTwo = value => value * 2;
const addFive = value => value + 5;
const result = addFive(multiplyByTwo(3));
9. Use object literals to simplify object creation and definition
// 传统对象创建
const person = {
 firstName: 'John',
 lastName: 'Doe',
 age: 30,
 };
// 对象字面量简化
const firstName = 'John';
const lastName = 'Doe';
const age = 30;
const person = { firstName, lastName, age };
10. Standard naming

Naming is the most frequent operation in writing code, such as classes, properties, methods, parameters, etc. Use appropriate naming and comments to improve code readability.

// 不好的
const x = 10; // 设置x的值为10
function a(b) {
 return b * 2; // 返回b的两倍
}
// 好的
const speed = 10; // 设置速度为10
function double(value) {
 return value * 2; // 返回输入值的两倍
}
11. If conditional expressions should not be too complicated

Simple conditional judgment logic uses if else or ternary operators. You can still understand what you are talking about at a glance, but a large number of if elses and superimposed ternary operators are a nightmare for the receiver~~~

For complex logic, it is recommended to use the object Map writing method, which is in line with the logic of the human brain, has high readability and is comfortable to look at~~~

1. Ordinary if else
let txt = '';
if (falg) {
 txt = "成功"
} else {
 txt = "失败"
}
2. Ternary operator
let txt = flag ? "成功" : "失败";
3. Multiple if else
let txt = '';
if (status == 1) {
 txt = "成功";
} else if (status == 2) {
 txt = "失败";
} else if (status == 3) {
 txt = "进行中";
} else {
 txt = "未开始";
}
4,switch case
let txt = '';
switch (status) {
 case 1:
 txt = "成功";
 break;
 case 2:
 txt = "成功";
 break;
 case 3:
 txt = "进行中";
 break;
 default:
 txt = "未开始";
}
5. Object writing method
const statusMap = {
 1: "成功",
 2: "失败",
 3: "进行中",
 4: "未开始"
}
//调用直接 statusMapp[status]
6. Map writing method
const actions = new Map([
 [1, "成功"],
 [2, "失败"],
 [3, "进行中"],
 [4, "未开始"]
])
// 调用直接 actions.get(status)
12. Encapsulate conditional statements

Same as above, the more conditions in the if, the less conducive it is to the maintenance of the receiver and the understanding of the human brain. At first glance, it looks like a bunch of logic. Multiple logic should be broken down into whole parts.

// 不好的
if (fsm.state === 'fetching' && isEmpty(listNode)) {
 // ...
}

// 好的
shouldShowSpinner(fsm, listNode){
 return fsm.state === 'fetching' && isEmpty(listNode)
}
if(shouldShowSpinner(fsm, listNode)){
 //...doSomething
}
13. Classes and Methods Single Responsibility

If the code is too long, it will look very complicated at first glance and make people not want to read on. At the same time, the code with too long methods may be confusing to read, and people do not know which codes are the functions of the same business. Functions should only do one thing. Functional writing advocates currying. Each function has one function and can be split and assembled.

// 不好的
function createFile(name, temp) {
 if (temp) {
   fs.create(`./temp/${name}`);
 } else {
   fs.create(name);
 }
}

// 好的
function createFile(name) {
 fs.create(name);
}

function createTempFile(name) {
 createFile(`./temp/${name}`)
}
14. Object.assign assigns default value to default object

Object.assign() This method can copy all properties of one or more source objects to the target object, thereby merging objects.

// 不好的
const menuConfig = {
 title: null,
 body: 'Bar',
 buttonText: null,
 cancellable: true
};
function createMenu(config) {
 config.title = config.title || 'Foo';
 config.body = config.body || 'Bar';
 config.buttonText = config.buttonText || 'Baz';
 config.cancellable = config.cancellable === undefined ?
 config.cancellable : true;
}
createMenu(menuConfig);

// 好的
const menuConfig = {
 title: 'Order',
 buttonText: 'Send',
 cancellable: true
};
function createMenu(config) {
 Object.assign({
   title: 'Foo',
   body: 'Bar',
   buttonText: 'Baz',
   cancellable: true 
 }, config)
}
createMenu(menuConfig);
15. It is best to have two or less function parameters.
/ 不好的
function createMenu(title, body, buttonText, cancellable) {
 // ...
}

// 好的
const menuConfig = {
 title: 'Foo',
 body: 'Bar',
 buttonText: 'Baz',
 cancellable: true
};
function createMenu(config){
 // ...
}

createMenu(menuConfig)

Guess you like

Origin blog.csdn.net/shanghai597/article/details/131728048