如何写好代码(4)——函数篇其二

课程 shanhuhai 1203℃ 0评论

不要使用单例模式

单例模式是一个反模式。

  1. 单例模式常用于全局实例,这样导致代码里隐藏了依赖关系,而不是通过接口公开依赖关系
  2. 单利模式导致了代码的紧耦合 。 这样导致单元测试难以实现。
  3. 单例模式的状态贯穿整个应用程序的整个生命周期,导致难以进行单元测试, 因为每个单元测试应该彼此独立

不好的

class DBConnection
{
    private static $instance;

    private function __construct(string $dsn)
    {
        // ...
    }

    public static function getInstance(): DBConnection
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    // ...
}

$singleton = DBConnection::getInstance();

好的


class DBConnection { public function __construct(string $dsn) { // ... } // ... }

封装条件语句

不好的

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

好的


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

避免使用反义判断

不好的


function isShopNotOpen(Shop $shop){ //... }

好的


function isShopOpen(Shop $shop){ //... }

避免使用条件语句

如果你的函数有条件预计,包括if ,switch,这就说明你的函数干了不止一件事,可以是用多态来实现同样 任务。关于PHP 多态参考PHP多态

不好的

class Airplane
{
    // ...

    public function getCruisingAltitude(): int
    {
        switch ($this->type) {
            case '777':
                return $this->getMaxAltitude() - $this->getPassengerCount();
            case 'Air Force One':
                return $this->getMaxAltitude();
            case 'Cessna':
                return $this->getMaxAltitude() - $this->getFuelExpenditure();
        }
    }
}

interface Airplane { // ... public function getCruisingAltitude(): int; } class Boeing777 implements Airplane { // ... public function getCruisingAltitude(): int { return $this->getMaxAltitude() - $this->getPassengerCount(); } } class AirForceOne implements Airplane { // ... public function getCruisingAltitude(): int { return $this->getMaxAltitude(); } } class Cessna implements Airplane { // ... public function getCruisingAltitude(): int { return $this->getMaxAltitude() - $this->getFuelExpenditure(); } }

避免类型检查

  1. 参数中规定类型
  2. 使用PHP严格模式

移除无用代码

不再被调用的代码应该移除,他会保存在版本库中,不用担心找不回来。

总结

本课主要介绍了以下内容:
1. 不要使用单例模式, 单例模式是一种反模式, 但模式隐藏了依赖关系, 并且导致代码难以测试
2. 封装条件判断语句, 提升代码可读性
3. 避免使用反义判断
4. 函数中避免使用条件语句,使用条件预计意味着函数做了不止一件事,应该使用多态或其他方式分拆函数
5. 移出无用代码
6. 避免类型检查

作业

检查自己的代码,使用3个技巧,优化自己的代码, 提交优化前和优化后的代码

转载请注明:大后端 » 如何写好代码(4)——函数篇其二

付费咨询
喜欢 (3)or分享 (0)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址