# 第006期.如何才能写出一手整洁的好代码？(上篇)

2021-05-13

“Master programmers think of systems as stories to be told rather than programs to be written”

​  — Uncle Bob.

## 什么样的代码才算是整洁的好代码

C++之父Bjarne Stroustrup说过：

“I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations. Clean code does one thing well.”

“我喜欢优雅和高效的代码。代码逻辑应当直截了当，让缺陷难以隐藏；尽量减少依赖关系，使之便于维护；依据某种分层战略完善错误处理代码；西能调至最优，省得引诱别人做没规矩的优化，搞出一堆混乱来。整洁的代码只做好一件事。”

Object Oriented Analysis and Design with Applications，《面向对象分析与设计》的作者Grady Booch认为：

“Clean code is simple and direct. Clean code reads like well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.”

Eclipse战略，OTI公司创始人，Dave Thomas讲过：

“Clean code can be read, and enhanced by a developer other than its original author. It has unit and acceptance tests. It has meaningful names. It provides one way rather than many ways for doing one thing. It has minimal depen- dencies, which are explicitly defined, and pro- vides a clear and minimal API. Code should be literate since depending on the language, not all necessary information can be expressed clearly in code alone.”

### 一、从起好名字名字开始

#### 名字要见名知意

//糟糕的名字let a = Date.today;//好的名字let today = Date.today;

#### 使用组合方式来起名

var elapsedTimeInDays;var daysSinceCreation;var dasySinceModification;var fileAgeInDays;

#### 起一个好类名

/**独立的页面**/class PageHome;class PageAbout;class PageShop;class PageCategory;/**组件的名字**/class CompButton;class CompNavBar;class CompPhoneNumber;class CompDashBoard;

#### 怎样给函数（方法）起个好名字

function createUser(){}function deletePhoto(){}//事件处理函数function handleLogin(){}function handleChangePassword(){}

#### 保持命名的一致性

function fetchUserInfo(){}function fetchProductInfo(){}function fetchActiveInfo(){}