经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » PHP » 查看文章
PHP 代码简洁之道(小结)
来源:jb51  时间:2019/10/17 9:05:32  对本文有异议

介绍

Robert C.Martin's 的 软件工程师准则 Clean Code 同样适用于 PHP。它并不是一个编码风格指南,它指导我们用 PHP 写出具有可读性,可复用性且可分解的代码。

并非所有的准则都必须严格遵守,甚至一些已经成为普遍的约定。这仅仅作为指导方针,其中许多都是 Clean Code 作者们多年来的经验。

灵感来自于 clean-code-javascript

尽管许多开发者依旧使用 PHP 5 版本,但是这篇文章中绝大多数例子都是只能在 PHP 7.1 + 版本下运行。

变量

使用有意义的且可读的变量名

不友好的:

  1. $ymdstr = $moment->format('y-m-d');

友好的:

  1. $currentDate = $moment->format('y-m-d');

对同类型的变量使用相同的词汇

不友好的:

  1. getUserInfo();
  2. getUserData();
  3. getUserRecord();
  4. getUserProfile();

友好的:

  1. getUser();

使用可搜索的名称(第一部分)

我们阅读的代码超过我们写的代码。所以我们写出的代码需要具备可读性、可搜索性,这一点非常重要。要我们去理解程序中没有名字的变量是非常头疼的。让你的变量可搜索吧!

不具备可读性的代码:

  1. // 见鬼的 448 是什么意思?
  2. $result = $serializer->serialize($data, 448);

具备可读性的:

  1. $json = $serializer->serialize($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

使用可搜索的名称(第二部分)

不好的:

  1. // 见鬼的 4 又是什么意思?
  2. if ($user->access & 4) {
  3. // ...
  4. }

好的方式:

  1. class User
  2. {
  3. const ACCESS_READ = 1;
  4. const ACCESS_CREATE = 2;
  5. const ACCESS_UPDATE = 4;
  6. const ACCESS_DELETE = 8;
  7. }
  8.  
  9. if ($user->access & User::ACCESS_UPDATE) {
  10. // do edit ...
  11. }
  12.  

使用解释性变量

不好:

  1. $address = 'One Infinite Loop, Cupertino 95014';
  2. $cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/';
  3. preg_match($cityZipCodeRegex, $address, $matches);
  4.  
  5. saveCityZipCode($matches[1], $matches[2]);
  6.  

一般:

这个好点,但我们仍严重依赖正则表达式。

  1. $address = 'One Infinite Loop, Cupertino 95014';
  2. $cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/';
  3. preg_match($cityZipCodeRegex, $address, $matches);
  4.  
  5. [, $city, $zipCode] = $matches;
  6. saveCityZipCode($city, $zipCode);
  7.  

很棒:

通过命名子模式减少对正则表达式的依赖。

  1. $address = 'One Infinite Loop, Cupertino 95014';
  2. $cityZipCodeRegex = '/^[^,]+,\s*(?<city>.+?)\s*(?<zipCode>\d{5})$/';
  3. preg_match($cityZipCodeRegex, $address, $matches);
  4.  
  5. saveCityZipCode($matches['city'], $matches['zipCode']);
  6.  

避免嵌套太深和提前返回 (第一部分)

使用太多 if else 表达式会导致代码难以理解。

明确优于隐式。

不好:

  1. function isShopOpen($day): bool
  2. {
  3. if ($day) {
  4. if (is_string($day)) {
  5. $day = strtolower($day);
  6. if ($day === 'friday') {
  7. return true;
  8. } elseif ($day === 'saturday') {
  9. return true;
  10. } elseif ($day === 'sunday') {
  11. return true;
  12. } else {
  13. return false;
  14. }
  15. } else {
  16. return false;
  17. }
  18. } else {
  19. return false;
  20. }
  21. }

很棒:

  1. function isShopOpen(string $day): bool
  2. {
  3. if (empty($day)) {
  4. return false;
  5. }
  6.  
  7. $openingDays = [
  8. 'friday', 'saturday', 'sunday'
  9. ];
  10.  
  11. return in_array(strtolower($day), $openingDays, true);
  12. }
  13.  

避免嵌套太深和提前返回 (第二部分)

不好:

  1. function fibonacci(int $n)
  2. {
  3. if ($n < 50) {
  4. if ($n !== 0) {
  5. if ($n !== 1) {
  6. return fibonacci($n - 1) + fibonacci($n - 2);
  7. } else {
  8. return 1;
  9. }
  10. } else {
  11. return 0;
  12. }
  13. } else {
  14. return 'Not supported';
  15. }
  16. }

很棒:

  1. function fibonacci(int $n): int
  2. {
  3. if ($n === 0 || $n === 1) {
  4. return $n;
  5. }
  6.  
  7. if ($n > 50) {
  8. throw new \Exception('Not supported');
  9. }
  10.  
  11. return fibonacci($n - 1) + fibonacci($n - 2);
  12. }
  13.  

避免心理映射

不要迫使你的代码阅读者翻译变量的意义。

明确优于隐式。

不好:

  1. $l = ['Austin', 'New York', 'San Francisco'];
  2.  
  3. for ($i = 0; $i < count($l); $i++) {
  4. $li = $l[$i];
  5. doStuff();
  6. doSomeOtherStuff();
  7. // ...
  8. // ...
  9. // ...
  10. // Wait, what is `$li` for again?
  11. dispatch($li);
  12. }
  13.  

很棒:

  1. $locations = ['Austin', 'New York', 'San Francisco'];
  2.  
  3. foreach ($locations as $location) {
  4. doStuff();
  5. doSomeOtherStuff();
  6. // ...
  7. // ...
  8. // ...
  9. dispatch($location);
  10. }
  11.  

不要增加不需要的上下文

如果类名或对象名告诉你某些东西后,请不要在变量名中重复。

小坏坏:

  1. class Car
  2. {
  3. public $carMake;
  4. public $carModel;
  5. public $carColor;
  6.  
  7. //...
  8. }
  9.  

好的方式:

  1. class Car
  2. {
  3. public $make;
  4. public $model;
  5. public $color;
  6.  
  7. //...
  8. }

使用默认参数而不是使用短路运算或者是条件判断

不好的做法:

这是不太好的因为 $breweryName 可以是 NULL.

  1. function createMicrobrewery($breweryName = 'Hipster Brew Co.'): void
  2. {
  3. // ...
  4. }

还算可以的做法:

这个做法比上面的更加容易理解,但是它需要很好的去控制变量的值.

  1. function createMicrobrewery($name = null): void
  2. {
  3. $breweryName = $name ?: 'Hipster Brew Co.';
  4. // ...
  5. }

好的做法:

你可以使用 类型提示 而且可以保证 $breweryName 不会为空 NULL.

  1. function createMicrobrewery(string $breweryName = 'Hipster Brew Co.'): void
  2. {
  3. // ...
  4. }

对比

使用 相等运算符

不好的做法:

  1. $a = '42';
  2. $b = 42;

使用简单的相等运算符会把字符串类型转换成数字类型

  1. if( $a != $b ) {
  2. //这个条件表达式总是会通过
  3. }

表达式 $a != $b 会返回 false 但实际上它应该是 true !
字符串类型 '42' 是不同于数字类型的 42

好的做法:
使用全等运算符会对比类型和值

  1. if( $a !== $b ) {
  2. //这个条件是通过的
  3. }

表达式 $a !== $b 会返回 true。

函数

函数参数(2 个或更少)

限制函数参数个数极其重要
这样测试你的函数容易点。有超过 3 个可选参数会导致一个爆炸式组合增长,你会有成吨独立参数情形要测试。

无参数是理想情况。1 个或 2 个都可以,最好避免 3 个。
再多就需要加固了。通常如果你的函数有超过两个参数,说明他要处理的事太多了。 如果必须要传入很多数据,建议封装一个高级别对象作为参数。

不友好的:

  1. function createMenu(string $title, string $body, string $buttonText, bool $cancellable): void
  2. {
  3. // ...
  4. }

友好的:

  1. class MenuConfig
  2. {
  3. public $title;
  4. public $body;
  5. public $buttonText;
  6. public $cancellable = false;
  7. }
  8.  
  9. $config = new MenuConfig();
  10. $config->title = 'Foo';
  11. $config->body = 'Bar';
  12. $config->buttonText = 'Baz';
  13. $config->cancellable = true;
  14.  
  15. function createMenu(MenuConfig $config): void
  16. {
  17. // ...
  18. }
  19.  

函数应该只做一件事情

这是迄今为止软件工程最重要的原则。函数做了超过一件事情时,它们将变得难以编写、测试、推导。 而函数只做一件事情时,重构起来则非常简单,同时代码阅读起来也非常清晰。掌握了这个原则,你就会领先许多其他的开发者。

不好的:

  1. function emailClients(array $clients): void
  2. {
  3. foreach ($clients as $client) {
  4. $clientRecord = $db->find($client);
  5. if ($clientRecord->isActive()) {
  6. email($client);
  7. }
  8. }
  9. }

好的:

  1. function emailClients(array $clients): void
  2. {
  3. $activeClients = activeClients($clients);
  4. array_walk($activeClients, 'email');
  5. }
  6.  
  7. function activeClients(array $clients): array
  8. {
  9. return array_filter($clients, 'isClientActive');
  10. }
  11.  
  12. function isClientActive(int $client): bool
  13. {
  14. $clientRecord = $db->find($client);
  15.  
  16. return $clientRecord->isActive();
  17. }
  18.  

函数的名称要说清楚它做什么

不好的例子:

  1. class Email
  2. {
  3. //...
  4.  
  5. public function handle(): void
  6. {
  7. mail($this->to, $this->subject, $this->body);
  8. }
  9. }
  10.  
  11. $message = new Email(...);
  12. // What is this? A handle for the message? Are we writing to a file now?
  13. $message->handle();
  14.  

很好的例子:

  1. class Email
  2. {
  3. //...
  4.  
  5. public function send(): void
  6. {
  7. mail($this->to, $this->subject, $this->body);
  8. }
  9. }
  10.  
  11. $message = new Email(...);
  12. // Clear and obvious
  13. $message->send();
  14.  

函数只能是一个抽象级别

当你有多个抽象层次时,你的函数功能通常是做太多了。 分割函数功能使得重用性和测试更加容易。.

不好:

  1. function parseBetterJSAlternative(string $code): void
  2. {
  3. $regexes = [
  4. // ...
  5. ];
  6.  
  7. $statements = explode(' ', $code);
  8. $tokens = [];
  9. foreach ($regexes as $regex) {
  10. foreach ($statements as $statement) {
  11. // ...
  12. }
  13. }
  14.  
  15. $ast = [];
  16. foreach ($tokens as $token) {
  17. // lex...
  18. }
  19.  
  20. foreach ($ast as $node) {
  21. // parse...
  22. }
  23. }
  24.  

同样不是很好:

我们已经完成了一些功能,但是 parseBetterJSAlternative() 功能仍然非常复杂,测试起来也比较麻烦。

  1. function tokenize(string $code): array
  2. {
  3. $regexes = [
  4. // ...
  5. ];
  6.  
  7. $statements = explode(' ', $code);
  8. $tokens = [];
  9. foreach ($regexes as $regex) {
  10. foreach ($statements as $statement) {
  11. $tokens[] = /* ... */;
  12. }
  13. }
  14.  
  15. return $tokens;
  16. }
  17.  
  18. function lexer(array $tokens): array
  19. {
  20. $ast = [];
  21. foreach ($tokens as $token) {
  22. $ast[] = /* ... */;
  23. }
  24.  
  25. return $ast;
  26. }
  27.  
  28. function parseBetterJSAlternative(string $code): void
  29. {
  30. $tokens = tokenize($code);
  31. $ast = lexer($tokens);
  32. foreach ($ast as $node) {
  33. // parse...
  34. }
  35. }
  36.  

很好的:

最好的解决方案是取出 parseBetterJSAlternative() 函数的依赖关系.

  1. class Tokenizer
  2. {
  3. public function tokenize(string $code): array
  4. {
  5. $regexes = [
  6. // ...
  7. ];
  8.  
  9. $statements = explode(' ', $code);
  10. $tokens = [];
  11. foreach ($regexes as $regex) {
  12. foreach ($statements as $statement) {
  13. $tokens[] = /* ... */;
  14. }
  15. }
  16.  
  17. return $tokens;
  18. }
  19. }
  20.  
  21. class Lexer
  22. {
  23. public function lexify(array $tokens): array
  24. {
  25. $ast = [];
  26. foreach ($tokens as $token) {
  27. $ast[] = /* ... */;
  28. }
  29.  
  30. return $ast;
  31. }
  32. }
  33.  
  34. class BetterJSAlternative
  35. {
  36. private $tokenizer;
  37. private $lexer;
  38.  
  39. public function __construct(Tokenizer $tokenizer, Lexer $lexer)
  40. {
  41. $this->tokenizer = $tokenizer;
  42. $this->lexer = $lexer;
  43. }
  44.  
  45. public function parse(string $code): void
  46. {
  47. $tokens = $this->tokenizer->tokenize($code);
  48. $ast = $this->lexer->lexify($tokens);
  49. foreach ($ast as $node) {
  50. // parse...
  51. }
  52. }
  53. }
  54.  

不要用标示作为函数的参数

标示就是在告诉大家,这个方法里处理很多事。前面刚说过,一个函数应当只做一件事。 把不同标示的代码拆分到多个函数里。

不友好的:

  1. function createFile(string $name, bool $temp = false): void
  2. {
  3. if ($temp) {
  4. touch('./temp/'.$name);
  5. } else {
  6. touch($name);
  7. }
  8. }

友好的:

  1. function createFile(string $name): void
  2. {
  3. touch($name);
  4. }
  5.  
  6. function createTempFile(string $name): void
  7. {
  8. touch('./temp/'.$name);
  9. }
  10.  

避免副作用

一个函数应该只获取数值,然后返回另外的数值,如果在这个过程中还做了其他的事情,我们就称为副作用。副作用可能是写入一个文件,修改某些全局变量,或者意外的把你全部的钱给了陌生人。

现在,你的确需要在一个程序或者场合里要有副作用,像之前的例子,你也许需要写一个文件。你需要做的是把你做这些的地方集中起来。不要用几个函数和类来写入一个特定的文件。只允许使用一个服务来单独实现。

重点是避免常见陷阱比如对象间共享无结构的数据、使用可以写入任何的可变数据类型、不集中去处理这些副作用。如果你做了这些你就会比大多数程序员快乐。

不好的:

  1. // 这个全局变量在函数中被使用
  2. // 如果我们在别的方法中使用这个全局变量,有可能我们会不小心将其修改为数组类型
  3. $name = 'Ryan McDermott';
  4.  
  5. function splitIntoFirstAndLastName(): void
  6. {
  7. global $name;
  8.  
  9. $name = explode(' ', $name);
  10. }
  11.  
  12. splitIntoFirstAndLastName();
  13.  
  14. var_dump($name); // ['Ryan', 'McDermott'];
  15.  

推荐的:

  1. function splitIntoFirstAndLastName(string $name): array
  2. {
  3. return explode(' ', $name);
  4. }
  5.  
  6. $name = 'Ryan McDermott';
  7. $newName = splitIntoFirstAndLastName($name);
  8.  
  9. var_dump($name); // 'Ryan McDermott';
  10. var_dump($newName); // ['Ryan', 'McDermott'];
  11.  

不要定义全局函数

在很多语言中定义全局函数是一个坏习惯,因为你定义的全局函数可能与其他人的函数库冲突,并且,除非在实际运用中遇到异常,否则你的 API 的使用者将无法觉察到这一点。接下来我们来看看一个例子:当你想有一个配置数组,你可能会写一个 config() 的全局函数,但是这样会与其他人定义的库冲突。

不好的:

  1. function config(): array
  2. {
  3. return [
  4. 'foo' => 'bar',
  5. ]
  6. }

好的:

  1. class Configuration
  2. {
  3. private $configuration = [];
  4.  
  5. public function __construct(array $configuration)
  6. {
  7. $this->configuration = $configuration;
  8. }
  9.  
  10. public function get(string $key): ?string
  11. {
  12. return isset($this->configuration[$key]) ? $this->configuration[$key] : null;
  13. }
  14. }
  15.  

获取配置需要先创建 Configuration 类的实例,如下:

  1. $configuration = new Configuration([
  2. 'foo' => 'bar',
  3. ]);

现在,在你的应用中必须使用 Configuration 的实例了。

不要使用单例模式

单例模式是个 反模式。 以下转述 Brian Button 的观点:

单例模式常用于 全局实例, 这么做为什么不好呢? 因为在你的代码里 你隐藏了应用的依赖关系,而没有通过接口公开依赖关系 。避免全局的东西扩散使用是一种 代码味道.
单例模式违反了 单一责任原则: 依据的事实就是 单例模式自己控制自身的创建和生命周期.
单例模式天生就导致代码紧 耦合。这使得在许多情况下用伪造的数据 难于测试。
单例模式的状态会留存于应用的整个生命周期。 这会对测试产生第二次打击,你只能让被严令需要测试的代码运行不了收场,根本不能进行单元测试。为何?因为每一个单元测试应该彼此独立。
还有些来自 Misko Hevery 的深入思考,关于单例模式的问题根源

不好的示范:

  1. class DBConnection
  2. {
  3. private static $instance;
  4.  
  5. private function __construct(string $dsn)
  6. {
  7. // ...
  8. }
  9.  
  10. public static function getInstance(): DBConnection
  11. {
  12. if (self::$instance === null) {
  13. self::$instance = new self();
  14. }
  15.  
  16. return self::$instance;
  17. }
  18.  
  19. // ...
  20. }
  21.  
  22. $singleton = DBConnection::getInstance();
  23.  

好的示范:

  1. class DBConnection
  2. {
  3. public function __construct(string $dsn)
  4. {
  5. // ...
  6. }
  7.  
  8. // ...
  9. }
  10.  

用 DSN 进行配置创建的 DBConnection 类实例。

  1. $connection = new DBConnection($dsn);

现在就必须在你的应用中使用 DBConnection 的实例了。

封装条件语句

不友好的:

  1. if ($article->state === 'published') {
  2. // ...
  3. }

友好的:

  1. if ($article->isPublished()) {
  2. // ...
  3. }

避免用反义条件判断

不友好的:

  1. function isDOMNodeNotPresent(\DOMNode $node): bool
  2. {
  3. // ...
  4. }
  5.  
  6. if (!isDOMNodeNotPresent($node))
  7. {
  8. // ...
  9. }
  10.  

友好的:

  1. function isDOMNodePresent(\DOMNode $node): bool
  2. {
  3. // ...
  4. }
  5.  
  6. if (isDOMNodePresent($node)) {
  7. // ...
  8. }
  9.  

避免使用条件语句

这听起来像是个不可能实现的任务。 当第一次听到这个时,大部分人都会说,“没有 if 语句,我该怎么办?” 答案就是在很多情况下你可以使用多态性来实现同样的任务。 接着第二个问题来了, “听着不错,但我为什么需要那样做?”,这个答案就是我们之前所学的干净代码概念:一个函数应该只做一件事情。如果你的类或函数有 if 语句,这就告诉了使用者你的类或函数干了不止一件事情。 记住,只要做一件事情。

不好的:

  1. class Airplane
  2. {
  3. // ...
  4.  
  5. public function getCruisingAltitude(): int
  6. {
  7. switch ($this->type) {
  8. case '777':
  9. return $this->getMaxAltitude() - $this->getPassengerCount();
  10. case 'Air Force One':
  11. return $this->getMaxAltitude();
  12. case 'Cessna':
  13. return $this->getMaxAltitude() - $this->getFuelExpenditure();
  14. }
  15. }
  16. }
  17.  

好的:

  1. interface Airplane
  2. {
  3. // ...
  4.  
  5. public function getCruisingAltitude(): int;
  6. }
  7.  
  8. class Boeing777 implements Airplane
  9. {
  10. // ...
  11.  
  12. public function getCruisingAltitude(): int
  13. {
  14. return $this->getMaxAltitude() - $this->getPassengerCount();
  15. }
  16. }
  17.  
  18. class AirForceOne implements Airplane
  19. {
  20. // ...
  21.  
  22. public function getCruisingAltitude(): int
  23. {
  24. return $this->getMaxAltitude();
  25. }
  26. }
  27.  
  28. class Cessna implements Airplane
  29. {
  30. // ...
  31.  
  32. public function getCruisingAltitude(): int
  33. {
  34. return $this->getMaxAltitude() - $this->getFuelExpenditure();
  35. }
  36. }
  37.  

避免类型检测 (第 1 部分)

PHP 是无类型的,这意味着你的函数可以接受任何类型的参数。
有时这种自由会让你感到困扰,并且他会让你自然而然的在函数中使用类型检测。有很多方法可以避免这么做。
首先考虑 API 的一致性。

不好的:

  1. function travelToTexas($vehicle): void
  2. {
  3. if ($vehicle instanceof Bicycle) {
  4. $vehicle->pedalTo(new Location('texas'));
  5. } elseif ($vehicle instanceof Car) {
  6. $vehicle->driveTo(new Location('texas'));
  7. }
  8. }

好的:

  1. function travelToTexas(Traveler $vehicle): void
  2. {
  3. $vehicle->travelTo(new Location('texas'));
  4. }

避免类型检查(第 2 部分)

如果你正在使用像 字符串、数值、或数组这样的基础类型,你使用的是 PHP 版本是 PHP 7+,并且你不能使用多态,但仍然觉得需要使用类型检测,这时,你应该考虑 类型定义 或 严格模式。它为您提供了标准 PHP 语法之上的静态类型。
手动进行类型检查的问题是做这件事需要这么多的额外言辞,你所得到的虚假的『类型安全』并不能弥补丢失的可读性。保持你的代码简洁,编写良好的测试,并且拥有好的代码审查。
否则,使用 PHP 严格的类型声明或严格模式完成所有这些工作。

不好的:

  1. function combine($val1, $val2): int
  2. {
  3. if (!is_numeric($val1) || !is_numeric($val2)) {
  4. throw new \Exception('Must be of type Number');
  5. }
  6.  
  7. return $val1 + $val2;
  8. }
  9.  

好的:

  1. function combine(int $val1, int $val2): int
  2. {
  3. return $val1 + $val2;
  4. }

移除无用代码

无用代码和重复代码一样糟糕。 如果没有被调用,就应该把它删除掉,没必要将它保留在你的代码库中!当你需要它的时候,可以在你的历史版本中找到它。

Bad:

  1. function oldRequestModule(string $url): void
  2. {
  3. // ...
  4. }
  5.  
  6. function newRequestModule(string $url): void
  7. {
  8. // ...
  9. }
  10.  
  11. $request = newRequestModule($requestUrl);
  12. inventoryTracker('apples', $request, 'www.inventory-awesome.io');
  13.  

Good:

  1. function requestModule(string $url): void
  2. {
  3. // ...
  4. }
  5.  
  6. $request = requestModule($requestUrl);
  7. inventoryTracker('apples', $request, 'www.inventory-awesome.io');
  8.  

对象和数据结构

使用对象封装

在 PHP 中,你可以在方法中使用关键字,如 public, protected and private。
使用它们,你可以任意的控制、修改对象的属性。

当你除获取对象属性外还想做更多的操作时,你不需要修改你的代码
当 set 属性时,易于增加参数验证。
封装的内部表示。
容易在获取和设置属性时添加日志和错误处理。
继承这个类,你可以重写默认信息。
你可以延迟加载对象的属性,比如从服务器获取数据。
此外,这样的方式也符合 OOP 开发中的 [开闭原则](# 开闭原则 (OCP))

不好的:

  1. class BankAccount
  2. {
  3. public $balance = 1000;
  4. }
  5.  
  6. $bankAccount = new BankAccount();
  7.  
  8. // Buy shoes...
  9. $bankAccount->balance -= 100;

好的:

  1. class BankAccount
  2. {
  3. private $balance;
  4.  
  5. public function __construct(int $balance = 1000)
  6. {
  7. $this->balance = $balance;
  8. }
  9.  
  10. public function withdraw(int $amount): void
  11. {
  12. if ($amount > $this->balance) {
  13. throw new \Exception('Amount greater than available balance.');
  14. }
  15.  
  16. $this->balance -= $amount;
  17. }
  18.  
  19. public function deposit(int $amount): void
  20. {
  21. $this->balance += $amount;
  22. }
  23.  
  24. public function getBalance(): int
  25. {
  26. return $this->balance;
  27. }
  28. }
  29.  
  30. $bankAccount = new BankAccount();
  31.  
  32. // Buy shoes...
  33. $bankAccount->withdraw($shoesPrice);
  34.  
  35. // Get balance
  36. $balance = $bankAccount->getBalance();
  37.  

让对象拥有 private/protected 属性的成员

  • public 公有方法和属性对于变化来说是最危险的,因为一些外部的代码可能会轻易的依赖他们,但是你没法控制那些依赖他们的代码。 类的变化对于类的所有使用者来说都是危险的。
  • protected 受保护的属性变化和 public 公有的同样危险,因为他们在子类范围内是可用的。也就是说 public 和 protected 之间的区别仅仅在于访问机制,只有封装才能保证属性是一致的。任何在类内的变化对于所有继承子类来说都是危险的 。
  • private 私有属性的变化可以保证代码 只对单个类范围内的危险 (对于修改你是安全的,并且你不会有其他类似堆积木的影响 Jenga effect).

因此,请默认使用 private 属性,只有当需要对外部类提供访问属性的时候才采用 public/protected 属性。

更多的信息可以参考Fabien Potencier 写的针对这个专栏的文章blog post .

Bad:

  1. class Employee
  2. {
  3. public $name;
  4.  
  5. public function __construct(string $name)
  6. {
  7. $this->name = $name;
  8. }
  9. }
  10.  
  11. $employee = new Employee('John Doe');
  12. echo 'Employee name: '.$employee->name; // Employee name: John Doe
  13.  

Good:

  1. class Employee
  2. {
  3. private $name;
  4.  
  5. public function __construct(string $name)
  6. {
  7. $this->name = $name;
  8. }
  9.  
  10. public function getName(): string
  11. {
  12. return $this->name;
  13. }
  14. }
  15.  
  16. $employee = new Employee('John Doe');
  17. echo 'Employee name: '.$employee->getName(); // Employee name: John Doe


组合优于继承

正如 the Gang of Four 所著的 设计模式 中所说,
我们应该尽量优先选择组合而不是继承的方式。使用继承和组合都有很多好处。
这个准则的主要意义在于当你本能的使用继承时,试着思考一下组合是否能更好对你的需求建模。
在一些情况下,是这样的。

接下来你或许会想,“那我应该在什么时候使用继承?”
答案依赖于你的问题,当然下面有一些何时继承比组合更好的说明:

  1. 你的继承表达了 “是一个” 而不是 “有一个” 的关系(例如人类 “是” 动物,而用户 “有” 用户详情)。
  2. 你可以复用基类的代码(人类可以像动物一样移动)。
  3. 你想通过修改基类对所有派生类做全局的修改(当动物移动时,修改它们的能量消耗)。

糟糕的:

  1. class Employee
  2. {
  3. private $name;
  4. private $email;
  5.  
  6. public function __construct(string $name, string $email)
  7. {
  8. $this->name = $name;
  9. $this->email = $email;
  10. }
  11.  
  12. // ...
  13. }
  14.  
  15. // 不好,因为Employees "有" taxdata
  16. // 而EmployeeTaxData不是Employee类型的
  17.  
  18. class EmployeeTaxData extends Employee
  19. {
  20. private $ssn;
  21. private $salary;
  22.  
  23. public function __construct(string $name, string $email, string $ssn, string $salary)
  24. {
  25. parent::__construct($name, $email);
  26.  
  27. $this->ssn = $ssn;
  28. $this->salary = $salary;
  29. }
  30.  
  31. // ...
  32. }
  33.  

棒棒哒:

  1. class EmployeeTaxData
  2. {
  3. private $ssn;
  4. private $salary;
  5.  
  6. public function __construct(string $ssn, string $salary)
  7. {
  8. $this->ssn = $ssn;
  9. $this->salary = $salary;
  10. }
  11.  
  12. // ...
  13. }
  14.  
  15. class Employee
  16. {
  17. private $name;
  18. private $email;
  19. private $taxData;
  20.  
  21. public function __construct(string $name, string $email)
  22. {
  23. $this->name = $name;
  24. $this->email = $email;
  25. }
  26.  
  27. public function setTaxData(string $ssn, string $salary)
  28. {
  29. $this->taxData = new EmployeeTaxData($ssn, $salary);
  30. }
  31.  
  32. // ...
  33. }
  34.  

避免流式接口

流式接口 是一种面向对象 API 的方法,旨在通过方法链 Method chaining 来提高源代码的可阅读性.

流式接口虽然需要一些上下文,需要经常构建对象,但是这种模式减少了代码的冗余度 (例如: PHPUnit Mock Builder
或 Doctrine Query Builder)

但是同样它也带来了很多麻烦:

  1. 破坏了封装 Encapsulation
  2. 破坏了原型 Decorators
  3. 难以模拟测试 mock
  4. 使得多次提交的代码难以理解

更多信息可以参考 Marco Pivetta 撰写的关于这个专题的文章blog post

Bad:

  1. class Car
  2. {
  3. private $make = 'Honda';
  4. private $model = 'Accord';
  5. private $color = 'white';
  6.  
  7. public function setMake(string $make): self
  8. {
  9. $this->make = $make;
  10.  
  11. // NOTE: Returning this for chaining
  12. return $this;
  13. }
  14.  
  15. public function setModel(string $model): self
  16. {
  17. $this->model = $model;
  18.  
  19. // NOTE: Returning this for chaining
  20. return $this;
  21. }
  22.  
  23. public function setColor(string $color): self
  24. {
  25. $this->color = $color;
  26.  
  27. // NOTE: Returning this for chaining
  28. return $this;
  29. }
  30.  
  31. public function dump(): void
  32. {
  33. var_dump($this->make, $this->model, $this->color);
  34. }
  35. }
  36.  
  37. $car = (new Car())
  38. ->setColor('pink')
  39. ->setMake('Ford')
  40. ->setModel('F-150')
  41. ->dump();
  42.  

Good:

  1. class Car
  2. {
  3. private $make = 'Honda';
  4. private $model = 'Accord';
  5. private $color = 'white';
  6.  
  7. public function setMake(string $make): void
  8. {
  9. $this->make = $make;
  10. }
  11.  
  12. public function setModel(string $model): void
  13. {
  14. $this->model = $model;
  15. }
  16.  
  17. public function setColor(string $color): void
  18. {
  19. $this->color = $color;
  20. }
  21.  
  22. public function dump(): void
  23. {
  24. var_dump($this->make, $this->model, $this->color);
  25. }
  26. }
  27.  
  28. $car = new Car();
  29. $car->setColor('pink');
  30. $car->setMake('Ford');
  31. $car->setModel('F-150');
  32. $car->dump();
  33.  

SOLID

SOLID 是 Michael Feathers 推荐的便于记忆的首字母简写,它代表了 Robert Martin 命名的最重要的五个面向对象编程设计原则:

  • S: 职责单一原则 (SRP)
  • O: 开闭原则 (OCP)
  • L: 里氏替换原则 (LSP)
  • I: 接口隔离原则 (ISP)
  • D: 依赖反转原则 (DIP)

职责单一原则 Single Responsibility Principle (SRP)

正如 Clean Code 书中所述,"修改一个类应该只为一个理由"。人们总是容易去用一堆方法 "塞满" 一个类,就好像当我们坐飞机上只能携带一个行李箱时,会把所有的东西都塞到这个箱子里。这样做带来的后果是:从逻辑上讲,这样的类不是高内聚的,并且留下了很多以后去修改它的理由。

将你需要修改类的次数降低到最小很重要,这是因为,当类中有很多方法时,修改某一处,你很难知晓在整个代码库中有哪些依赖于此的模块会被影响。

比较糟:

  1. class UserSettings
  2. {
  3. private $user;
  4.  
  5. public function __construct(User $user)
  6. {
  7. $this->user = $user;
  8. }
  9.  
  10. public function changeSettings(array $settings): void
  11. {
  12. if ($this->verifyCredentials()) {
  13. // ...
  14. }
  15. }
  16.  
  17. private function verifyCredentials(): bool
  18. {
  19. // ...
  20. }
  21. }
  22.  

棒棒哒:

  1. class UserAuth
  2. {
  3. private $user;
  4.  
  5. public function __construct(User $user)
  6. {
  7. $this->user = $user;
  8. }
  9.  
  10. public function verifyCredentials(): bool
  11. {
  12. // ...
  13. }
  14. }
  15.  
  16. class UserSettings
  17. {
  18. private $user;
  19. private $auth;
  20.  
  21. public function __construct(User $user)
  22. {
  23. $this->user = $user;
  24. $this->auth = new UserAuth($user);
  25. }
  26.  
  27. public function changeSettings(array $settings): void
  28. {
  29. if ($this->auth->verifyCredentials()) {
  30. // ...
  31. }
  32. }
  33. }
  34.  

开闭原则 (OCP)

如 Bertrand Meyer 所述,"软件实体 (类,模块,功能,等) 应该对扩展开放,但对修改关闭." 这意味着什么?这个原则大体上是指你应该允许用户在不修改已有代码情况下添加功能.

坏的:

  1. abstract class Adapter
  2. {
  3. protected $name;
  4.  
  5. public function getName(): string
  6. {
  7. return $this->name;
  8. }
  9. }
  10.  
  11. class AjaxAdapter extends Adapter
  12. {
  13. public function __construct()
  14. {
  15. parent::__construct();
  16.  
  17. $this->name = 'ajaxAdapter';
  18. }
  19. }
  20.  
  21. class NodeAdapter extends Adapter
  22. {
  23. public function __construct()
  24. {
  25. parent::__construct();
  26.  
  27. $this->name = 'nodeAdapter';
  28. }
  29. }
  30.  
  31. class HttpRequester
  32. {
  33. private $adapter;
  34.  
  35. public function __construct(Adapter $adapter)
  36. {
  37. $this->adapter = $adapter;
  38. }
  39.  
  40. public function fetch(string $url): Promise
  41. {
  42. $adapterName = $this->adapter->getName();
  43.  
  44. if ($adapterName === 'ajaxAdapter') {
  45. return $this->makeAjaxCall($url);
  46. } elseif ($adapterName === 'httpNodeAdapter') {
  47. return $this->makeHttpCall($url);
  48. }
  49. }
  50.  
  51. private function makeAjaxCall(string $url): Promise
  52. {
  53. // request and return promise
  54. }
  55.  
  56. private function makeHttpCall(string $url): Promise
  57. {
  58. // request and return promise
  59. }
  60. }
  61.  

好的:

  1. interface Adapter
  2. {
  3. public function request(string $url): Promise;
  4. }
  5.  
  6. class AjaxAdapter implements Adapter
  7. {
  8. public function request(string $url): Promise
  9. {
  10. // request and return promise
  11. }
  12. }
  13.  
  14. class NodeAdapter implements Adapter
  15. {
  16. public function request(string $url): Promise
  17. {
  18. // request and return promise
  19. }
  20. }
  21.  
  22. class HttpRequester
  23. {
  24. private $adapter;
  25.  
  26. public function __construct(Adapter $adapter)
  27. {
  28. $this->adapter = $adapter;
  29. }
  30.  
  31. public function fetch(string $url): Promise
  32. {
  33. return $this->adapter->request($url);
  34. }
  35. }
  36.  

里氏代换原则 (LSP)

这是一个简单概念的可怕术语。它通常被定义为 “如果 S 是 T 的一个子类型,则 T 型对象可以替换为 S 型对象”
(i.e., S 类型的对象可以替换 T 型对象) 在不改变程序的任何理想属性的情况下 (正确性,任务完成度,etc.)." 这是一个更可怕的定义.
这个的最佳解释是,如果你有个父类和一个子类,然后父类和子类可以互换使用而不会得到不正确的结果。这或许依然令人疑惑,所以我们来看下经典的正方形 - 矩形例子。几何定义,正方形是矩形,但是,如果你通过继承建立了 “IS-a” 关系的模型,你很快就会陷入麻烦。.

不好的:

  1. class Rectangle
  2. {
  3. protected $width = 0;
  4. protected $height = 0;
  5.  
  6. public function render(int $area): void
  7. {
  8. // ...
  9. }
  10.  
  11. public function setWidth(int $width): void
  12. {
  13. $this->width = $width;
  14. }
  15.  
  16. public function setHeight(int $height): void
  17. {
  18. $this->height = $height;
  19. }
  20.  
  21. public function getArea(): int
  22. {
  23. return $this->width * $this->height;
  24. }
  25. }
  26.  
  27. class Square extends Rectangle
  28. {
  29. public function setWidth(int $width): void
  30. {
  31. $this->width = $this->height = $width;
  32. }
  33.  
  34. public function setHeight(int $height): void
  35. {
  36. $this->width = $this->height = $height;
  37. }
  38. }
  39.  
  40. /**
  41. * @param Rectangle[] $rectangles
  42. */
  43. function renderLargeRectangles(array $rectangles): void
  44. {
  45. foreach ($rectangles as $rectangle) {
  46. $rectangle->setWidth(4);
  47. $rectangle->setHeight(5);
  48. $area = $rectangle->getArea(); // BAD: Will return 25 for Square. Should be 20.
  49. $rectangle->render($area);
  50. }
  51. }
  52.  
  53. $rectangles = [new Rectangle(), new Rectangle(), new Square()];
  54. renderLargeRectangles($rectangles);
  55.  

优秀的:

  1. abstract class Shape
  2. {
  3. abstract public function getArea(): int;
  4.  
  5. public function render(int $area): void
  6. {
  7. // ...
  8. }
  9. }
  10.  
  11. class Rectangle extends Shape
  12. {
  13. private $width;
  14. private $height;
  15.  
  16. public function __construct(int $width, int $height)
  17. {
  18. $this->width = $width;
  19. $this->height = $height;
  20. }
  21.  
  22. public function getArea(): int
  23. {
  24. return $this->width * $this->height;
  25. }
  26. }
  27.  
  28. class Square extends Shape
  29. {
  30. private $length;
  31.  
  32. public function __construct(int $length)
  33. {
  34. $this->length = $length;
  35. }
  36.  
  37. public function getArea(): int
  38. {
  39. return pow($this->length, 2);
  40. }
  41. }
  42.  
  43. /**
  44. * @param Rectangle[] $rectangles
  45. */
  46. function renderLargeRectangles(array $rectangles): void
  47. {
  48. foreach ($rectangles as $rectangle) {
  49. $area = $rectangle->getArea();
  50. $rectangle->render($area);
  51. }
  52. }
  53.  
  54. $shapes = [new Rectangle(4, 5), new Rectangle(4, 5), new Square(5)];
  55. renderLargeRectangles($shapes);
  56.  

接口隔离原则 (ISP)

ISP 指出 "客户不应该被强制依赖于他们用不到的接口."

一个好的例子来观察证实此原则的是针对需要大量设置对象的类,不要求客户端设置大量的选项是有益的,因为多数情况下他们不需要所有的设置。使他们可选来避免产生一个 “臃肿的接口”.

坏的:

  1. interface Employee
  2. {
  3. public function work(): void;
  4.  
  5. public function eat(): void;
  6. }
  7.  
  8. class Human implements Employee
  9. {
  10. public function work(): void
  11. {
  12. // ....working
  13. }
  14.  
  15. public function eat(): void
  16. {
  17. // ...... eating in lunch break
  18. }
  19. }
  20.  
  21. class Robot implements Employee
  22. {
  23. public function work(): void
  24. {
  25. //.... working much more
  26. }
  27.  
  28. public function eat(): void
  29. {
  30. //.... robot can't eat, but it must implement this method
  31. }
  32. }

好的:

并不是每个工人都是雇员,但每个雇员都是工人.

  1. interface Workable
  2. {
  3. public function work(): void;
  4. }
  5.  
  6. interface Feedable
  7. {
  8. public function eat(): void;
  9. }
  10.  
  11. interface Employee extends Feedable, Workable
  12. {
  13. }
  14.  
  15. class Human implements Employee
  16. {
  17. public function work(): void
  18. {
  19. // ....working
  20. }
  21.  
  22. public function eat(): void
  23. {
  24. //.... eating in lunch break
  25. }
  26. }
  27.  
  28. // robot can only work
  29. class Robot implements Workable
  30. {
  31. public function work(): void
  32. {
  33. // ....working
  34. }
  35. }

依赖反转原则 (DIP)

这一原则规定了两项基本内容:

高级模块不应依赖于低级模块。两者都应该依赖于抽象.
抽象类不应依赖于实例。实例应该依赖于抽象.
一开始可能很难去理解,但是你如果工作中使用过 php 框架(如 Symfony), 你应该见过以依赖的形式执行这一原则
依赖注入 (DI). 虽然他们不是相同的概念,DIP 可以让高级模块不需要了解其低级模块的详细信息而安装它们.
通过依赖注入可以做到。这样做的一个巨大好处是减少了模块之间的耦合。耦合是一种非常糟糕的开发模式,因为它使您的代码难以重构.

不好的:

  1. class Employee
  2. {
  3. public function work(): void
  4. {
  5. // ....working
  6. }
  7. }
  8.  
  9. class Robot extends Employee
  10. {
  11. public function work(): void
  12. {
  13. //.... working much more
  14. }
  15. }
  16.  
  17. class Manager
  18. {
  19. private $employee;
  20.  
  21. public function __construct(Employee $employee)
  22. {
  23. $this->employee = $employee;
  24. }
  25.  
  26. public function manage(): void
  27. {
  28. $this->employee->work();
  29. }
  30. }

优秀的:

  1. interface Employee
  2. {
  3. public function work(): void;
  4. }
  5.  
  6. class Human implements Employee
  7. {
  8. public function work(): void
  9. {
  10. // ....working
  11. }
  12. }
  13.  
  14. class Robot implements Employee
  15. {
  16. public function work(): void
  17. {
  18. //.... working much more
  19. }
  20. }
  21.  
  22. class Manager
  23. {
  24. private $employee;
  25.  
  26. public function __construct(Employee $employee)
  27. {
  28. $this->employee = $employee;
  29. }
  30.  
  31. public function manage(): void
  32. {
  33. $this->employee->work();
  34. }
  35. }
  36.  

别写重复代码 (DRY)

试着去遵循 DRY 原则。

尽你最大的努力去避免复制代码,它是一种非常糟糕的行为,复制代码通常意味着当你需要变更一些逻辑时,你需要修改不止一处。

试想一下,如果你在经营一家餐厅,并且你需要记录你仓库的进销记录:包括所有的土豆,洋葱,大蒜,辣椒,等等。如果你使用多个表格来管理进销记录,当你用其中一些土豆做菜时,你需要更新所有的表格。如果你只有一个列表的话就只需要更新一个地方。

通常情况下你复制代码的原因可能是它们大多数都是一样的,只不过有两个或者多个略微不同的逻辑,但是由于这些区别,最终导致你写出了两个或者多个隔离的但大部分相同的方法,移除重复的代码意味着用一个 function/module/class 创建一个能处理差异的抽象。

正确的抽象是非常关键的,这正是为什么你必须学习遵守在 Classes 章节展开讨论的的 SOLID 原则,不合理的抽象比复制代码更糟糕,所以请务必谨慎!说了这么多,如果你能设计一个合理的抽象,就去实现它!最后再说一遍,不要写重复代码,否则你会发现当你想修改一个逻辑时,你必须去修改多个地方!

糟糕的:

  1. function showDeveloperList(array $developers): void
  2. {
  3. foreach ($developers as $developer) {
  4. $expectedSalary = $developer->calculateExpectedSalary();
  5. $experience = $developer->getExperience();
  6. $githubLink = $developer->getGithubLink();
  7. $data = [
  8. $expectedSalary,
  9. $experience,
  10. $githubLink
  11. ];
  12.  
  13. render($data);
  14. }
  15. }
  16.  
  17. function showManagerList(array $managers): void
  18. {
  19. foreach ($managers as $manager) {
  20. $expectedSalary = $manager->calculateExpectedSalary();
  21. $experience = $manager->getExperience();
  22. $githubLink = $manager->getGithubLink();
  23. $data = [
  24. $expectedSalary,
  25. $experience,
  26. $githubLink
  27. ];
  28.  
  29. render($data);
  30. }
  31. }
  32.  

好的:

  1. function showList(array $employees): void
  2. {
  3. foreach ($employees as $employee) {
  4. $expectedSalary = $employee->calculateExpectedSalary();
  5. $experience = $employee->getExperience();
  6. $githubLink = $employee->getGithubLink();
  7. $data = [
  8. $expectedSalary,
  9. $experience,
  10. $githubLink
  11. ];
  12.  
  13. render($data);
  14. }
  15. }
  16.  

非常好:

最好让你的代码紧凑一点。

  1. function showList(array $employees): void
  2. {
  3. foreach ($employees as $employee) {
  4. render([
  5. $employee->calculateExpectedSalary(),
  6. $employee->getExperience(),
  7. $employee->getGithubLink()
  8. ]);
  9. }
  10. }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号