phanalist

E7 Too many parameters.

When a method has too many parameters, it means that something is going on that is challenging to detect.

<?php

class Maintainance{

  public function execute(
     Hammer $hammer,
     Screw $screw,
     Screwdriver $screwDriver,
     Nails $nails,
     Paint $paint,
     SandingPaper $sandingPaper,
     Painting $painting){
  }
}

If you analyze the type of parameters. Some of the parameters are actually for different kinds of porpuses. The current threshold is five and still readable. But there are methods out there that have way more parameters.

Solution

The solution can be challenging, depending on your code and what it does. But I will break down the maintenance class even more in this scenario.

Without having the body of execute(), I know it consists of multiple activities. Painting a wall or an object, removing or adding something to the wall that has screws in it, and hanging a painting.

<?php 

// Maintainance.php
class Maintainance{

  public function execute(Activity ...$activities){

      $activities = func_get_args();
      foreach($activities as $activity){
      $tools = $activity->getTools();

      /// Use tools;

    }
  }
}

/// activity.php
interface Activity{

  /* Return the rights tools or let the Maintainance.class
   * know that you will be using a specific tool.
   */
  public function getTools():array;

}

// Paint.php
class Paint implements Activity {
  
  public function getTools():array{

      return [
        
      ];
  }
}

// Sanding.php
class Sanding implements Activity{
  
  public function getTools():array{

      return [
        
      ];
  }

}
// Painting
class Painting implement Activity{
  public function getTools():array{

      return [
        
      ];
  }
}

// ElectricitySocket.php
class ElectricitySocket implements Activity{

   public function getTools():array{

      return [
        
      ];
  }
}

Now you can add new Activities without changing the signature of execute and breaking things that you are not thinking about. This way, you do not need to pass too many parameters to the execute method. The amount of code has drastically increased, but I see that as acceptable.