大家好,我是若川,诚邀你进群交流学习。今天分享一篇相对轻松的代码简洁之道。学习源码系列、面试、年度总结、JS基础系列
内容出自《代码整洁之道》、Alex Kondov[1]的博文tao-of-react[2]和《Clean Code of Javascript》
代码整洁有什么用?
思路清晰,降低bug几率
更容易维护,利于团队协作
看起来舒服,提高效率
......
软件质量与代码整洁度成正比 --Robert.C.Martin
软件设计3R层次结构:readable, reusable, and refactorable[3] 可读性、可重用性、可重构性
下面这些原则是作者提出的一些最佳实践,但不是强制约束
关于命名
1.使用有意义且易读的变量名
???? const yyyymmdstr = moment().format("YYYY/MM/DD");???? const currentDate = moment().format("YYYY/MM/DD");
2.使用有意义的变量代替数组下标
????
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})?$/;
const [_, city, zipCode] = address.match(cityZipCodeRegex) || [];
saveCityZipCode(city, zipCode);
3.变量名要简洁,不要附加无用信息
????
const Car = {carMake: "Honda",carModel: "Accord",carColor: "Blue"
};
function paintCar(car, color) {car.carColor = color;
}????
const Car = {make: "Honda",model: "Accord",color: "Blue"
};
function paintCar(car, color) {car.color = color;
}
4.消除魔术字符串
???? setTimeout(blastOff, 86400000);???? const MILLISECONDS_PER_DAY = 60 * 60 * 24 * 1000; //86400000;
setTimeout(blastOff, MILLISECONDS_PER_DAY);
5.使用默认参数替代短路运算符
????
function createMicrobrewery(name) {const breweryName = name || "Hipster Brew Co.";// ...
}????
function createMicrobrewery(name = "Hipster Brew Co.") {// ...
}
关于函数
1.一个函数只做一件事的好处在于易于理解、易于测试。
????
function emailClients(clients) {clients.forEach(client => {const clientRecord = database.lookup(client);if (clientRecord.isActive()) {email(client);}});
}????
function emailActiveClients(clients) {clients.filter(isActiveClient).forEach(email);
}
function isActiveClient(client) {const clientRecord = database.lookup(client);return clientRecord.isActive();
}---------------------分割线-----------------------????
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}`);
}
2.函数参数不多于2个,如果有很多参数就利用object传递,并使用解构。
推荐使用解构的几个原因:
看到函数签名可以立即了解有哪些参数
解构能克隆传递到函数中的参数对象的值(浅克隆),有助于防止副作用.
linter可以提示有哪些参数未被使用
????
function createMenu(title, body, buttonText, cancellable) {// ...
}
createMenu("Foo", "Bar", "Baz", true);????
function createMenu({ title, body, buttonText, cancellable }) {// ...
}
createMenu({title: "Foo",body: "Bar",buttonText: "Baz",cancellable: true
});
3.函数名应该直接反映函数的作用
????
function addToDate(date, month) {// ...
}
const date = new Date();
// It's hard to tell from the function name what is added
addToDate(date, 1);????
function addMonthToDate(month, date) {// ...
}
const date = new Date();
addMonthToDate(1, date);
4.一个函数的抽象层级不要太多,如果你的函数做了太多事,就需要把它拆分成多个函数
????
function parseBetterJSAlternative(code) {const REGEXES = [// ...];const statements = code.split(" ");const tokens = [];REGEXES.forEach(REGEX => {statements.forEach(statement => {// ...});});const ast = [];tokens.forEach(token => {// lex...});ast.forEach(node => {// parse...});
}????
function parseBetterJSAlternative(code) {const tokens = tokenize(code);const syntaxTree = parse(tokens);syntaxTree.forEach(node => {// parse...});
}
function tokenize(code) {const REGEXES = [// ...];const statements = code.split(" ");const tokens = [];REGEXES.forEach(REGEX => {statements.forEach(statement => {tokens.push(/* ... */);});});return tokens;
}
function parse(tokens) {const syntaxTree = [];tokens.forEach(token => {syntaxTree.push(/* ... */);});return syntaxTree;
}
5.减少重复代码
????
function showDeveloperList(developers) {developers.forEach(developer => {const expectedSalary = developer.calculateExpectedSalary();const experience = developer.getExperience();const githubLink = developer.getGithubLink();const data = {expectedSalary,experience,githubLink};render(data);});
}
function showManagerList(managers) {managers.forEach(manager => {const expectedSalary = manager.calculateExpectedSalary();const experience = manager.getExperience();const portfolio = manager.getMBAProjects();const data = {expectedSalary,experience,portfolio};render(data);});
}????
function showEmployeeList(employees) {employees.forEach(employee => {const expectedSalary = employee.calculateExpectedSalary();const experience = employee.getExperience();const data = {expectedSalary,experience};switch (employee.type) {case "manager":data.portfolio = employee.getMBAProjects();break;case "developer":data.githubLink = employee.getGithubLink();break;}render(data);});
}
6.尽量使用纯函数 (函数式编程,not命令式编程)
????
const programmerOutput = [{name: "Uncle Bobby",linesOfCode: 500},{name: "Suzie Q",linesOfCode: 1500},{name: "Jimmy Gosling",linesOfCode: 150},{name: "Gracie Hopper",linesOfCode: 1000}
];
let totalOutput = 0;
for (let i = 0; i < programmerOutput.length; i++) {totalOutput += programmerOutput[i].linesOfCode;
}????
const programmerOutput = [{name: "Uncle Bobby",linesOfCode: 500},{name: "Suzie Q",linesOfCode: 1500},{name: "Jimmy Gosling",linesOfCode: 150},{name: "Gracie Hopper",linesOfCode: 1000}
];
const totalOutput = programmerOutput.reduce((totalLines, output) => totalLines + output.linesOfCode,0
);
7.注意函数的副作用
????
const addItemToCart = (cart, item) => {cart.push({ item, date: Date.now() });
};????
const addItemToCart = (cart, item) => {return [...cart, { item, date: Date.now() }];
};
8.不要过度优化
现代浏览器在运行时进行了大量的优化。很多时候,如果你再优化,那就是在浪费时间。
????
// On old browsers, each iteration with uncached `list.length` would be costly
// because of `list.length` recomputation. In modern browsers, this is optimized.
for (let i = 0, len = list.length; i < len; i++) {// ...
}????
for (let i = 0; i < list.length; i++) {// ...
}
关于注释
1.Comments are an apology, not a requirement. Good code mostly documents itself.
好的代码是自注释的
????
function hashIt(data) {// The hashlet hash = 0;// Length of stringconst length = data.length;// Loop through every character in datafor (let i = 0; i < length; i++) {// Get character code.const char = data.charCodeAt(i);// Make the hashhash = (hash << 5) - hash + char;// Convert to 32-bit integerhash &= hash;}
}????
function hashIt(data) {let hash = 0;const length = data.length;for (let i = 0; i < length; i++) {const char = data.charCodeAt(i);hash = (hash << 5) - hash + char;// Convert to 32-bit integerhash &= hash;}
}
2.git能做的事不要写在注释里
????
/*** 2016-12-20: Removed monads, didn't understand them (RM)* 2016-10-01: Improved using special monads (JP)* 2016-02-03: Removed type-checking (LI)* 2015-03-14: Added combine with type-checking (JR)*/
function combine(a, b) {return a + b;
}????
function combine(a, b) {return a + b;
}
关于组件
1.尽可能使用函数组件
函数式组件有更简单的语法,没有生命周期函数,构造函数。同样的逻辑和可靠性,函数式组件可以用更少的代码完成。
????
class Counter extends React.Component {state = {counter: 0,}constructor(props) {super(props)this.handleClick = this.handleClick.bind(this)}handleClick() {this.setState({ counter: this.state.counter + 1 })}render() {return (<div><p>counter: {this.state.counter}</p><button onClick={this.handleClick}>Increment</button></div>)}
}
????
function Counter() {const [counter, setCounter] = useState(0)handleClick = () => setCounter(counter + 1)return (<div><p>counter: {counter}</p><button onClick={handleClick}>Increment</button></div>)
}
2.函数组件中剥离逻辑代码
尽可能的把逻辑从组件中剥离出去,可以把必要的值用参数的形式传给工具类函数。在函数组件外组织你的逻辑让你能够更简单的去追踪 bug 和扩展你的功能。
????
export default function Component() {const [value, setValue] = useState('')function isValid() {// ...}return (<><inputvalue={value}onChange={e => setValue(e.target.value)}onBlur={validateInput}/><buttononClick={() => {if (isValid) {// ...}}}>Submit</button></>)
}????
function isValid(value) {// ...
}
export default function Component() {const [value, setValue] = useState('')return (<><inputvalue={value}onChange={e => setValue(e.target.value)}onBlur={validateInput}/><buttononClick={() => {if (isValid(value)) {// ...}}}>Submit</button></>)
}
3.控制组件长度,减少UI耦合
函数组件也是函数,同样要控制长度,如果组件太长,就要拆成多个组件
????
function Filters({ onFilterClick }) {return (<><p>Book Genres</p><ul><li><div onClick={() => onFilterClick('fiction')}>Fiction</div></li><li><div onClick={() => onFilterClick('classics')}>Classics</div></li><li><div onClick={() => onFilterClick('fantasy')}>Fantasy</div></li><li><div onClick={() => onFilterClick('romance')}>Romance</div></li></ul></>)
}// ???? Use loops and configuration objects
const GENRES = [{identifier: 'fiction',name: Fiction,},{identifier: 'classics',name: Classics,},{identifier: 'fantasy',name: Fantasy,},{identifier: 'romance',name: Romance,},
]function Filters({ onFilterClick }) {return (<><p>Book Genres</p><ul>{GENRES.map(genre => (<li><div onClick={() => onFilterClick(genre.identifier)}>{genre.name}</div></li>))}</ul></>)
}
4.尽量避免函数组件内再定义函数组件
不要在一个函数组件中再去书写一个函数组件。一个函数组件应该仅仅是一个函数。函数组件内部再定义函数组件,意味着内部的函数组件能够通过作用域访问到外层组件所有的 state 和 props,这样会使内部定义组件不可靠。把内部的组件移到外部,避免闭包和作用域的影响。
// ???? Don't write nested render functions
function Component() {function renderHeader() {return <header>...</header>}return <div>{renderHeader()}</div>
}
// ???? Extract it in its own component
import Header from '@modules/common/components/Header'
function Component() {return (<div><Header /></div>)
}
5.优化props
控制props数量、聚合props、完善渲染条件
如何把控 props 的量是一个值得商榷的问题。但是一个组件传递越多的 props 意味着它做的事情越多这是共识。当 props 达到一定数量的时候,意味着这个组件做的事情太多了。当props的数量达到5个以上的时候,这个组件就需要被拆分了。在某些极端诸如输入类型组件的情况下,可能拥有过多的props,但在通常情况下5个props能够满足大部分组件的需求。
提示:一个组件拥有越多的 props,越容易被 rerender。
一些场景下使用短路语法来进行条件渲染可能导致期望之外的问题,有可能会渲染一个 0 在界面上。避免这种情况发生,尽量使用三元操作符。尽管短路操作符能使代码变得简洁,但是三元操作符能够保证渲染的正确性。
// ???? Try to avoid short-circuit operators
function Component() {const count = 0return <div>{count && <h1>Messages: {count}</h1>}</div>
}
// ???? Use a ternary instead
function Component() {const count = 0return <div>{count ? <h1>Messages: {count}</h1> : null}</div>
}
关于其他
1.把组件放入单独的文件夹中
// ???? Don't keep all component files together
├── components├── Header.jsx├── Header.scss├── Header.test.jsx├── Footer.jsx├── Footer.scss├── Footer.test.jsx// ???? Move them in their own folder
├── components├── Header├── index.js├── Header.jsx├── Header.scss├── Header.test.jsx├── Footer├── index.js├── Footer.jsx├── Footer.scss├── Footer.test.jsx
2.尽量使用绝对路径
使用绝对路径可以在移动一个文件的时候能够尽量少的更改其它文件。绝对路径也能让你对所有依赖文件的出处一目了然。
(完)
最近组建了一个江西人的前端交流群,如果你是江西人可以加我微信 ruochuan12 私信 江西 拉你进群。
推荐阅读
我在阿里招前端,该怎么帮你(可进面试群)
毕业年限不长的前端焦虑和突破方法
前端抢饭碗系列之Vue项目如何做单元测试
老姚浅谈:怎么学JavaScript?
················· 若川简介 ·················
你好,我是若川,毕业于江西高校。现在是一名前端开发“工程师”。写有《学习源码整体架构系列》多篇,在知乎、掘金收获超百万阅读。
从2014年起,每年都会写一篇年度总结,已经写了7篇,点击查看年度总结。
同时,活跃在知乎@若川,掘金@若川。致力于分享前端开发经验,愿景:帮助5年内前端人走向前列。
点击上方卡片关注我、加个星标
今日话题
略。欢迎分享、收藏、点赞、在看我的公众号文章~