The Dark Boz The Dark Boz - 2 months ago 7
C# Question

Optimize switch between child class of same parent class

Hello
I want to know if there is a best practice code for this example or tips for make more simple.
All classes are classes children of Choix but all methods are override in the child class.
If I tried with Choix Choix =new AddTenant but without success
Thank you for any further help/answer

string arguments = args[0].ToLower();
bool load;
bool lauch;
bool result;
switch (arguments)
{
case "AddTenant":
AddTenant AddTenant = new AddTenant();
load = AddTenant.Load();
lauch = AddTenant.Lauch();
result = AddTenant.Result();
break;
case "BackupDb":
BackupDb BackupDb = new BackupDb();
load = BackupDb.Load();
lauch = BackupDb.Lauch();
result = BackupDb.Result();
break;
case "ExtractTenant":
ExtractTenant ExtractTenant = new ExtractTenant();
load = ExtractTenant.Load();
lauch = ExtractTenant.Lauch();
result = ExtractTenant.Result();
break;
case "InstallDb":
InstallDb InstallDb = new InstallDb();
load = InstallDb.Load();
lauch = InstallDb.Lauch();
result = InstallDb.Result();;
break;
case "RestoreDb":
RestoreDb RestoreDb = new RestoreDb();
load = RestoreDb.Load();
lauch = RestoreDb.Lauch();
result = RestoreDb.Result();
break;
case "UpgradeTenant":
UpgradeTenant UpgradeTenant = new UpgradeTenant();
load = UpgradeTenant.Load();
lauch = UpgradeTenant.Lauch();
result = UpgradeTenant.Result();
break;
default:
Help Help = new Help();
load = Help.Load();
lauch = Help.Lauch();
result = Help.Result();
break;
}
Console.WriteLine(load+" "+lauch+" "+result);

Answer

If the classes are child classes of Choix and methods are properly overriden, what you propose should work:

string arguments = args[0].ToLower();

Choix choix;
switch (arguments)
{
    case "AddTenant":
        choix = new AddTenant();
        break;
    case "BackupDb":
        choix = new BackupDb();
        break;
    case "ExtractTenant":
        choix = new ExtractTenant();
        break;
    case "InstallDb":
        choix = new InstallDb();
        break;
    case "RestoreDb":
        choix = new RestoreDb();
        break;
    case "UpgradeTenant":
        choix = new UpgradeTenant();
        break;
    default:
        choix = new Help();
        break;
}

bool load = choix.Load();
bool lauch = choix.Lauch();
bool result = choix.Result();

Console.WriteLine(load + " " + lauch + " " + result);

This is an option of how your classes should be looking like:

abstract class Choix
{
    public abstract bool Load();
    public abstract bool Lauch();
    public abstract bool Result();
}

class AddTenant : Choix
{
    public override bool Load()
    {
        // Load ...
        return true;
    }

    public override bool Lauch()
    {
        // Lauch ...
        return true;
    }

    public override bool Result()
    {
        // Result ...
        return true;
    }
}