lundi 22 février 2021

C# - Is it good practice to pass parameter from the factory (pattern) method to the returned strategy (pattern)?

Scenario: I'll have to convert different types (integer, bool, enums...). So i have created different strategies as this might extend in the future.

I created a factory class to select the approprioate strategy.

Is it a good practice to just pass the parameter to decide the strategy right further to the strategy-class itself as it will be used there anyway to proceed? Example: return new ConvertEnumToIntStrategy(valueToConvert)

Factory:

public static ConvertSourceValueStrategy GetStrategy(object valueToConvert)
{
    switch (valueToConvert)
    {
         case Enum e when e.GetType() == typeof(BeanstBerichtErhebung):
                return new ConvertBeanstBerichtErhebungToStringStrategy(); // pass valueToConvert?

         case Enum e:
                return new ConvertEnumToIntStrategy(); // pass valueToConvert?
         ...
     }
}

Example Strategy

public class ConvertEnumToIntStrategy : ConvertSourceValueStrategy
{
    public object Convert(object sourceValue)
    {
        return (int)sourceValue;
    }
}

Calling code:

var convertStrategy = ConvertSourceValueStrategyFactory.GetStrategy(sourceValue);
var valueToWrite = convertStrategy.Convert(sourceValue);

If i would pass the parameter, i could probably call it like the code below. But somebody could theoretically create a new strategy without a constructor for the parameter to pass as i can't force that with an Interface.

ConvertSourceValueStrategyFactory.GetStrategy(sourceValue).Convert();

Aucun commentaire:

Enregistrer un commentaire