dimanche 29 mai 2022

Remove switch in more generic way

I encountered this class:

public class CommandFactory
{
    private readonly Dictionary<string, ICommand> commands;
    private readonly IPrinterEmulator printerEmulator;

    public CommandFactory(IPrinterEmulator printerEmulator)
    {
        commands = new Dictionary<string, ICommand>();
        this.printerEmulator = printerEmulator;
    }

    public ICommand GetCommand(string cmdStr)
    {
        ICommand command;

        if (commands.ContainsKey(cmdStr))
        {
            command = commands[cmdStr];
        }
        else
        {
            command = GetConcreteCommand(printerEmulator, cmdStr);
            commands.Add(cmdStr, command);
        }

        return command;
    }

    private ICommand GetConcreteCommand(IPrinterEmulator printerEmulator, string commandStr)
    {
        return commandStr switch
        {
            "SetJob" => new SetJobCommand(printerEmulator),
            "GetJob" => new GetJobCommand(printerEmulator),
            _ => new NotReconizeCmd(printerEmulator),
        };
    }
}

I am wondering why the dictionary in class constructor wasn't prepopulated in fashion Dictionary<string,Func<ICommand, string>> selector, but rather using get command to gain reference to implementation?

I have feeling that there has to be more appropriate approach and I am sure that switch statement can be completely removed in this way. Your opinion?

Thank you in advance

Aucun commentaire:

Enregistrer un commentaire