BadToTheBone
BadToTheBone

Reputation: 185

Repeating blocks of code used throughout multiple functions in class - how to apply DRY

I am using php, I have a class with 10 functions which share some repeating code like in the following

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;
     }

     ...

}

Within the functions I placed "..." which represents code that differs in each function, however all 10 functions start with a empty local $t array, and end with $t being flattened and passed to another function, finally $this being returned.

How can we apply DRY to this, isit even possible? - I am thinking there maybe some way to write this once.

Regards

Upvotes: 2

Views: 356

Answers (1)

Yang
Yang

Reputation: 8711

Okay, to apply the DRY, you have to answer this question: What differs all the time and what remains the same? Seeing at your code, it looks obvious that only CAR | BIKE do differ. So according to this, you can abstract your calls, like this:

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');
     }
}

Upvotes: 2

Related Questions