lundi 18 mai 2020

Best way to split a large class

I have a large Product class (above 2000 lines and will get bigger in the future) and I started thinking about splitting it up in a more logical way so that it better follows the Single Responsibility Principle. For example, right now, on an afterSave() event I am sending the product data to an API via cURL. Here I usually have pairs of 2 methods, one responsible for getting some Product information and another for formatting that information into the Payload required by the API:

getAssociatedProducts()
apiAssociatedProductsPayload()
getChangedAttributes()
apiAttributesPayload()
getStockChanges()
apiStocksPayload()

And after I prepare the payload, I send it via an apiCurl() method.

I was thinking of creating a sparate API class, but I haven't got much experience with design patters, and the problem I have is that the methods for preparing the payload, which I would want to separate in the new class, aren't very reusable, seeing as they are product specific. For example:

protected function apiAssociatedProductsPayload($sku, $relationType, $associatedProducts) {

    $items = [];
    foreach($associatedProducts as $associatedProduct) {
        $items[] = [
            "sku" => $sku,
            "linkType" => $relationType,
            "linkedProductSku" => $associatedProduct["sku_".$relationType],
            "linkedProductType" => "simple",
            "position" => $associatedProduct["position"]
        ];
    };

    return ["items" => $items];
}

So in this case, my question is what's the best way to separate API and Product concerns, and which one should be responsible for which task? And how should I approach writing the payload methods that to my mind are API related, but are very dependent on the Product (so I don't see how I would reuse them in other classes)?

Aucun commentaire:

Enregistrer un commentaire