Writing Charming Code: The Key to Optimizing Readability, Maintainability, and Performance

This article summarizes the elegant writing of business logic that is often encountered in work development, and also summarizes the pain points when I was a newcomer and didn’t know how to start a business. I vaguely remember that I always felt that the code I wrote was not standardized.

After finishing writing, I still feel good, and I learned something again.

start of text

Why write elegant code?

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

There are mainly the following advantages:

  1. Readability : Easy to read and understand. Clear naming, concise syntax, and good code structure can make the intent of the code more clear, 降低理解代码的难度and improve the readability of the code.

  2. Maintainability : Easy to maintain. When the code logic is clear and the structure is concise, developers can 更快速地定位和修复bugexpand or modify functions. At the same time, highly readable code also helps subsequent code refactoring and optimization.

  3. Scalability : more scalable and flexible 灵活性. A clear code structure and concise coding style make it easier to add new functionality, modify existing functionality, or extend the code. In addition, concise code tends to be less dependent on specific implementation details, allowing more flexibility and substitutability.

  4. Error reduction and debugging time : 更容易写出正确的逻辑,减少了出错的概率. At the same time, when there is a problem with the code, the elegant and concise code is easier to debug and locate the error.

  5. Performance optimization : Concise code is usually more efficient, reducing unnecessary calculations and resource consumption. Streamlined code structure and algorithms can improve code execution efficiency and performance

Basic skills

1. Use arrow functions to simplify function definitions

// 传统函数定义
function add(a, b) {
 return a + b;
 }
  
 // 箭头函数简化
 const add = (a, b) => a + b;

2. Use destructuring assignment to simplify variable declaration

// 传统变量声明
const firstName = person.firstName;
const lastName = person.lastName;
// 解构赋值简化
const { firstName, lastName } = person;

3. String concatenation using template literals

// 传统字符串拼接
const greeting = 'Hello, ' + name + '!';
// 模板字面量简化
const greeting = `Hello, ${name}!`;

4. Using 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 manipulation

// 遍历数组并返回新数组
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. Simplify function arguments with object destructuring and default arguments

// 传统参数设置默认值
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. Use proper 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; // 返回输入值的两倍

Then play music and dance (actual combat)! ! !

combat

1. Elegantly write conditional judgment code

Simple conditional judgment logic if else or ternary operators, you can tell what you are talking about at a glance, but a large number of if elseternary operators that are superimposed together is the nightmare of the receiver~~~

Let me give you a case of ternary operator superposition. I actually encountered it in the project, and the CPU directly exploded~~~

<view>{
   
   {status===1?'成功': status===2 ? '失败' : status===3 ? '进行中' : '未开始' }}</view>

Probably like this, the specific project code is not easy to put here, as long as you understand it.

It is recommended to use the object Map writing method for complex logic, which is in line with the logic of the human brain, has high readability, and looks comfortable~~~

1. Ordinary if else

let txt = '';
if (falg) {
 txt = 成功
} else {
 txt = 失败
}

2. Ternary operator

let txt = flag ? 成功 : 失败;

3. Multiple if else

// param {status} status 活动状态:1:成功 2:失败 3:进行中 4:未开始
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

const statusMap = {
 1: 成功,
 2: 失败,
 3: 进行中,
 4: 未开始
}
//调用直接 statusMapp[status]

6. Map writing method

const actions = new Map([
 [1, 成功],
 [2, 失败],
 [3, 进行中],
 [4, 未开始]
])
// 调用直接 actions.get(status)

2. Encapsulate conditional statements

Same as above, the more conditions in the if, the more unfavorable it is to the maintenance of the receiver, and it is not conducive to the understanding of the human brain. At first glance, it is a bunch of logic. Multiple logical should 化零为整.

大脑:'别来碰我,让我静静'

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

3. Functions should only do one thing

The functional writing method is highly respected 柯里化, one function and one function, which 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}`)
}

one more chestnut

What the function does is the following:

  • traverse the clients array

  • During the traversal process, a new object clientRecord is obtained through the lookup function

  • Determine whether the isActive function in the clientRecord object returns true ,

    • The isActive function returns true , executes the email function and brings the current member over

// 不好的
function emailClients(clients) {
 clients.forEach((client) => {
   const clientRecord = database.lookup(client);
   if (clientRecord.isActive()) {
     email(client);
   }
 });
}
// 好的
function emailClients(clients) {
 clients
   .filter(isClientRecord)
   .forEach(email)
}
function isClientRecord(client) {
 const clientRecord = database.lookup(client);
 return clientRecord.isActive()
}

The bad chestnuts above look at it at first glance, does it feel like a bunch of codes are there, and I don’t even want to look at it for a while.

Good chestnuts, isn’t the logic clear and easy to read?

  • Using the filter function skillfully, open a function for the callback of the filter for conditional processing, and return the data that meets the conditions

  • Use forEach skillfully to execute the email function on qualified data

4. Object.assign assigns a default value to the default object

// 不好的
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);

5. It is best to have less than two function parameters

To say a thousand words and ten thousand is for elegance and good readability.

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

6. Use explanatory variables

Save flow, use the extension operator, for readability (saveCityZipCode(city, zipCode) readability is very good, know what the parameter is for)

// 不好的
const address = 'One Infinite Loop, Cupertino 95014';
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
saveCityZipCode(address.match(cityZipCodeRegex)[1], address.match(cityZipCodeRegex)[2]);
// 好的
const address = 'One Infinite Loop, Cupertino 95014';
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
cosnt [, city, zipCode] = address.match(cityZipCodeRegex) || [];
saveCityZipCode(city, zipCode)

When you want to perform more custom access/increase/change operations on the attributes in the class, use set/get

This is the first time I saw this wording, I don’t know what it means, my friends, I think of it as defineProperty in vue2

Object.defineProperty(data1,'age',{
 set:function(newAge){
   console.log(this.name+'现在'+newAge+'岁')
 },
 get:function(){
   return 18;
 }
})

It means that set will be triggered when assigning a value, and get will be triggered when getting a value.

Use the built-in attributes skillfully to improve performance.

class BankAccount {
 constructor(balance = 1000) {
   this._balance = balance;
 }
 // It doesn't have to be prefixed with `get` or `set` to be a
 //getter/setter
 set balance(amount) {
   console.log('set')
   if (verifyIfAmountCanBeSetted(amount)) {
     this._balance = amount;
   }
 }
 get balance() {
   console.log('get')
   return this._balance;
 }
 verifyIfAmountCanBeSetted(val) {
   // ...
 }
}
const bankAccount = new BankAccount();
// Buy shoes...
bankAccount.balance -= 100;
// Get balance
let balance = bankAccount.balance;

7. Make objects have private members - through closures

Closures are inherently privatized

// 不好的
const Employee = function(name) {
 this.name = name;
};
Employee.prototype.getName = function getName() {
 return this.name;
};
const employee = new Employee('John Doe');
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
delete employee.name;
console.log(`Employee name: ${employee.getName()}`); // Employee name: undefined
// 好的
const Employee = function(name){
 this.getName = function(){
   return name
 }
}
const employee = new Employee('John Doe');
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
delete employee.name;
console.log(`Employee name: ${employee.getName()}`); // Employee name: undefined

first example

advantage:

  • By 原型链共享方法saving memory space. All instance objects share the same  getName method, instead of creating an independent method for each instance object.

shortcoming:

  • There is no way to define private properties or methods directly in a constructor, 所有属性和方法都会被暴露在原型链上.

second example

advantage:

  • It can be inside the constructor 定义私有属性和方法and will not be exposed on the prototype chain of the object, providing better encapsulation.

shortcoming:

  • Every time an instance object is created, an independent method, 每个实例对象都有its own  getName method, takes up more memory space.

8. Using Method Chaining

链式写法It is also the highlight of the way of code elegance.

ps: The programmer who invented this must be from the backend. This kind of writing has been seen in the CI framework of PHP.

// 不好的
class Car {
 constructor() {
   this.make = 'Honda';
   this.model = 'Accord';
   this.color = 'white';
 }
 setMake(make) {
   this.make = make;
 }
 save() {
   console.log(this.make, this.model, this.color);
 }
}
const car = new Car();
car.setMake('Ford');
car.save();
// 好的
class Car {
 constructor() {
   this.make = 'Honda';
   this.model = 'Accord';
   this.color = 'white';
 }
 setMake(make) {
   this.make = make;
   // NOTE: return this是为了用链式写法
   return this;
 }
 save() {
   console.log(this.make, this.model, this.color);
   // NOTE:return this是为了用链式写法
   return this;
 }
}
const car = new Car()
 .setMake('Ford')
 .save();

After reading so many chestnuts above, my friend's thinking is much clearer, let's practice in your project.

What you will gain is the gratitude of your colleagues and receivers and the comfort in your own heart! ! !

end

I tried my best to put my notes and ideas here in this article, I hope it will be helpful to my friends.

Welcome to reprint, but please indicate the source.

Finally, I hope that my friends will give me a free like, and I wish you all your wishes come true, peace and joy.

Guess you like

Origin blog.csdn.net/qq_48652579/article/details/131364132