lundi 11 avril 2022

Implementing strategy when every strategy need different params

I have method that do 3 different thing based on user type, so i thought I can split it into strategies with factory that will return desired strategy based on user.type. So I will get:

strategy_interface.execute(product_id, user_id);

and then

strategy = strategy_factory.create(user.type);
strategy.execute(...);

but in reality method "execute" needs slighty different params for every user type:

if user.type is 1 then it needs only product_id
if user.type is 2 or 3 or 5 then it needs product_id and user_id
else it should only throw illegal_action_exception

I like my approach as it is easy to test. I have to check only instance type returned by factory but I have problem with that every returned strategy works differently. Maybe instead of universal factory I should do something like this:

if user.type is 1:
    strategy = new first_strategy();
    strategy.execute(...);
else if user.type is in(2, 3, 5):
    strategy = new second_strategy();
    strategy.execute(...);
throw new illegal_action_exception();

Aucun commentaire:

Enregistrer un commentaire