mardi 12 avril 2022

Is there a design pattern to avoid properties not set error in class

I have some legacy code I am trying to improve somewhat.

I have a Proxy class that accepts an apiKey. My application is always aware of this key. Therefore I can start with:

$proxy = new Proxy("api-key");

Next, depending on the shop, I need to find their credentials - and pass that in to the proxy class:

$proxy->setShop($shop); // $shop will be determined at runtime

Then I can make a request like:

$proxy->getItems()

However, if I have not setShop, then internally the code will fail. But, it cannot go in the construct because shop is not known yet.

I could delay construct to the point where I know the shop but that would involve passing around the apiKey which I would rather not do. I could create an intermediary class that creates the Proxy class for me, like a factory? And call that factory from the controller when the shop is known. I don't have a very strong opinion on if that is a good approach or not.

Is there a particular pattern here that I could use? I could just thrown an Exception if the shop isn't set with a clear message but that feels defeatist - but maybe I am wrong and maybe that is exactly the right thing to do.

So is there a particular design pattern to use in these situations?

Aucun commentaire:

Enregistrer un commentaire