I have a console application in .NET6 that receives 1 argument, and based on that, has to decide which operation will be executed. At first I had all the executions as static methods and everything being decided in a switch statement, but then refactored the action executions.
But now I’m still trying to figure out how to remove the switch statement in order for everything to become a bit more dynamic and not worrying about adding a new case, each time a new action is developed.
Basically trying to reach a solution (at least a “good” approach) were the developer should only worry about the coding of the action class itself and not going to the switch (the program should know what relates to what -> argument-to-action)
At the moment the main code is something as follow:
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
//validating args
if(!args.Any())
return;
switch (args.First())
{
case "action1":
case "action2":
case "action3":
break;
default:
return;
}
switch (args.First())
{
case "action1":
RunTheAction<Action1>();
break;
case "action2":
RunTheAction<Action2>();
break;
case "action3":
//todo RunTheAction<Action3>()
break;
//it keeps growing -> RunTheAction<>()
}
}
static void RunTheAction<T>() where T : IAction
{
var action = Activator.CreateInstance<T>();
action.Execute();
}
}
}
All action instances to be executed use the interface IAction:
internal interface IAction
{
void Execute();
}
internal class Action1 : IAction
{
public void Execute()
{
//do some action1 stuff
}
}
internal class Action2 : IAction
{
public void Execute()
{
//do some action2 stuff (different than action1 :) )
}
}
Constant strings relations with the actions
DevSurferPTPXO is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.