在类中的多个函数中重复使用的代码块 - 如何应用 DRY



我正在使用php,我有一个包含10个函数的类,它们共享一些重复的代码,如下所示

class A
{
    function car()
    {
        $t = [];
        ...
        ...
        $t .= 'CAR ' . implode(', ', $t);
        $this->someFunc($t);
        return $this;
     }

     function bike()
     {
        $t = [];
        ...
        ...
        $t .= 'BIKE ' . implode(', ', $t);
        $this->someFunc($t);
        return $this;
     }
     ...
}

在函数中,我放置了">...",它表示每个函数中不同的代码,但是所有 10 个函数都以一个空的本地$t数组开头,并以$t被展平并传递给另一个函数结束,最后$this返回。

我们如何将 DRY 应用于此,甚至可能吗? - 我想也许有办法写一次。

问候

好的,要应用 DRY,您必须回答这个问题:什么一直不同,什么保持不变?查看您的代码,很明显只有CAR | BIKE有所不同。因此,根据此,您可以抽象调用,如下所示:

class A
{
     protected function prepare($t, $type)
     {
        $t .= $type . implode(', ', $t);
        $this->addToString($t);
        return $this;
     }

     public function car()
     {
         $t = [];
         ....
         return $this->prepare($t, 'CAR');
     }
     public function bike()
     {
        $t = [];
        ...
        return $this->prepare($t, 'BIKE');
     }
}

最新更新