请注意写好代码的三个要点

482 阅读2分钟

命名

先来思考几个问题? 当阅读别人的代码时,你通过什么信息来理解代码是在做什么? 变量、函数和类是什么?

通常阅读别人的代码时,我们通过变量、函数和类来理解程序意图, 所以本质上变量、函数和类 是程序员和程序逻辑之间的接口。

因此,当你为变量、类和函数命名时,如果使用不清晰、不可描述的名称,你实际上是在混淆任何读代码的程序员的程序逻辑。

比如:

dxy

如果只看这个名字, 谁也猜不出是什么意思,你必须读更多的代码, 从上下文去推断

改成:

distanceBetweenXY

能够立即理解到 这个名称表示『距离x,y直接的距离』

好的代码是自解释的

“Clear and expressive code with few comments is far superior to cluttered and complex code with lots of comments.” — Robert C. Martin “清晰、表达力强、注释少的代码远优于包含大量注释的杂乱复杂代码。”—罗伯特·C·马丁

优化前:

// 检查一个工人是否有全部福利

if ((employee.flags != HOURLY_FLAG) && (employee.age > 65))

优化后:

if (employee.isEligibleForFullBenefits())

一个函数或者类只做一件事(单一职责)

如果你看过一个有几百行甚至几千行的函数,你就知道阅读、理解和修改是多么痛苦。代码注释只能起到微小的作用。

“Programming is breaking one big impossible task into several small possible tasks.”– Jazzwant “编程就是把一个大的不可能的任务分解成几个小的可能任务。”

好的的代码被分解成原子的块组。每个函数的目标应该是做一件事,每个类都应该致力于表示一个特定的概念。

putElephantIntoRefrigerator() 面向过程拆分:

openRefrigerator()

pushElephantIntoRefrigerator()

closeRefrigerator()

面向对象拆分:

class Elephant {} class Refrigerator { private isDoorOpen;privateisDoorOpen; private volume = [];

public function open(){
    $this->isDoorOpen = true;
}

public function close(){
    $this->isDoorOpen = false;
}

public function save($object){
    $volume[] = $object;
}

}

elephant=newElephant();elephant = new Elephant(); refrigerator = new Refrigerator(); refrigerator>open();refrigerator->open(); refrigerator->save(elephant);elephant); refrigerator->close();