mardi 30 juin 2020

How to refactor class with too many dependencies

I have a class with 20 dependencies injected in the constructor. The class implements an interface with one method called handle. Unfortunately, the implementation of that handle method uses ALOT of method chaining, so any variables that need to be shared between methods need to become private properties of the class, which contributes even more to the mess detection. The dependencies injected are classes that handle data hydration from an HTTP request, calling other web services for fulfilling business logic, persisting records, and ultimately creating an HTTP response object. There are external configurations that adjust the business logic applied to the request as well.

The example is hopefully enough to give you all a jist of what I'm dealing with. The real implementation is even worse.

class ResourceHandler implements HandlerInterface
{
    private $request;
    private $response;
    private $someWebServiceClient;
    private $requestToWebServiceRequestTransformer;
    private $databaseRepo;
    private $requestToDatabaseRecordTransformer;
    .
    .
    .
    private $cacher;
    private $logger;

    public function handle()
    {
        return $this
          ->buildRequest()
          ->checkThisDatabase()
          ->callThatWebService()
          ->storeSomeRecords()
          .
          .
          .
          ->buildResponse();
    }
}

interface HandlerInterface {
    public function handle();
}

Aucun commentaire:

Enregistrer un commentaire