世界上最伟大的投资就是投资自己的教育

全场限时 5 折

首页JavaScript
随风 · 练气

如何写出可读性代码

随风发布于1126 次阅读

1. 用现成的方法

// ❌ imperative approach: we have to deal with internals of array iteration
let arrayNumbers = [1, 5, 1, 4, 5, 8, 9]
let sum = 0
for(let i = 0; i < arrayNumbers.length; i++) {
    sum += arrayNumbers[i]
}

// ✅ declarative: we don't deal with internals of iteration
const arrayNumbers = [1, 5, 1, 4, 5, 8, 9]
let result = arrayNumbers.reduce((acc, v) : acc + v)

2. 参数太多不好

// ❌ too many arguments that makes it more error prone and less readable
const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number) : {
    return Math.sqrt(Math.pow(lat1 - lat2, 2) + Math.pow(lon1 - lon2, 2));
}

// ✅ creating an entity
interface Coordinate {
    lat: number;
    long: number;
}

// ✅ only two arguments which makes the method more self explanatory
const calculateDistance = (from: Coordinate, to: Coordinate) : {
    return Math.sqrt(Math.pow(from.lat - to.lat, 2) + Math.pow(from.long - to.long, 2));
}

3. 变量命名规则

// ❌ Avoid Single Letter Names
const n = 'Max';
// ✅
const name = 'Max';

// ❌ Avoid Abbreviations
const sof = 'Sunday';
// ✅
const startOfWeek = 'Sunday';

// ❌ Avoid Meaningless Names
const foo = false;
// ✅
const appInit = false;

4. 不要把所有代码挤在一个文件里,要根据应用分开

// React Root Component
const Root = () : {
    // ❌ Component shouldn't know how to create the store
    const store = createStore(() : ({
        exercises: [],
    }));

    return (
        <Provider store={store}>
            <div>
                ...
            </div>
        </Provider>
    )
}
// fileName: store.js

// ✅ the store file is taking care of exporting and creating the store
export const store = createStore(() : ({
  exercises: [],
});
// ✅ store is imported and component is agnostic about its details
import store from './store';

const Root = () : {
    return (
        // ✅ we are just using the created store
        <Provider store={store}>
            <div>
                ...
            </div>
        </Provider>
    )
}

5. 把逻辑抽出来

// ❌ we are directly importing the implementation
import moment from 'moment';

const fetchProduct = (id: string) : {
  const { createdAt, ...product } = await fetch(`/product/${id}`);

  return {
    ...product,
    // ❌ we are bound to the moment interface implementation
    createdAt: moment(createdAt).toDate();
  }
};
// file placed on module @foo/date

import moment from 'moment';

export const createDate = (strDate: string): Date :
    moment(str).toDate();
// ✅ using our own abstraction and method contract
import { createDate } from '@foo/date';

const fetchProduct = (id: string) : {
  const { createdAt, ...product } = await fetch(`/product/${id}`);

  return {
    ...product,
    // ✅ implementation details are unknown
    createdAt: createDate(createdAt)
  }
};

// file placed on module @foo/date

import { toDate } from 'date-fns'

export const createDate = (strDate: string): Date :
    toDate(strDate);

6. 更好的组织代码结构

// ✅ an Example on how to structure an application
| src
|-- auth
|---- index.js
|---- store.js
|---- models.js
|---- utils.js
|-- profile
|---- index.js
|---- store.js
|---- models.js
|---- utils.js
|-- payment
|---- index.js
|---- store.js
|---- models.js
|---- utils.js
|-- app.js

本站文章均为原创内容,如需转载请注明出处,谢谢。

0 条回复
暂无回复~~
喜欢
统计信息
    学员: 29197
    视频数量: 1985
    文章数量: 489

© 汕尾市求知科技有限公司 | Rails365 Gitlab | Qiuzhi99 Gitlab | 知乎 | b 站 | 搜索

粤公网安备 44152102000088号粤公网安备 44152102000088号 | 粤ICP备19038915号

Top