Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse file differently upon different version

EDIT: I've done some research about this, but have not been able to find a solution!

I'm reading a configuration from an XML file. The layout of the configuration is set for certain version. This version is in the first line of the XML, which is easy to extract.

What I would like to know is, what is the best way to actually parse this file/get another method, based on the version (so all 4 elements, the Major, Minor, Build and Revision).

Right now I've come up with this:

switch (version.Major)
{
    case 0:
        switch (version.Minor)
        {
            case 0:
                switch (version.Build)
                {
                    case 0:
                        switch (version.Revision)
                        {
                            case 0:
                                return VersionNone(doc);
                        }
                        break;
                }
                break;
        }
        break;
}
throw new NotImplementedException();

But I do not find this elegant (at all) and I feel like there is a way better way to do this.

Anyone who can help?

like image 972
Foitn Avatar asked Mar 21 '18 14:03

Foitn


2 Answers

For something like this i'd be tempted to build a dictionary of actions

Edit: Updated to include a document paramter in response to comment from OP

    Dictionary<string, Action<XmlDocument>> versionSpecificMethods = new Dictionary<string, Action<XmlDocument>>{
    {"1.0.0.0", DoStuff1},
    {"1.2.3.4", DoStuff2},
    {"3.1.7.182", DoStuff3}};

    private void RunMethodForVersion(string version, XmlDocument someXmlDoc)
    {
        var codeToRun = versionSpecificMethods[version];
        codeToRun.Invoke(someXmlDoc);
    }

    private static void DoStuff1(XmlDocument doc)
    {
        // Insert user code here
    }
like image 128
Andy P Avatar answered Nov 03 '22 00:11

Andy P


If you want to share code between version, you can try to use inheritance:

interface IConfig 
{
     string GetConnectionString();
     string GetUserSettings();
     int GetDelay();
}

class Version_1 : IConfig
{
     public virtual string GetConnectionString() { ... }
     public virtual string GetUserSettings { ... }
     public virtual int GetDelay();
}

class Version_1_1 : Version_1
{
    // Changed UserSetttings and delay in xml
    public override GetUserSettings { ... }
    public override int GetDelay { ... }
}

class Version_1_1_4 : Version_1_1
{
    // Changed delay in xml
    public override int GetDelay { ... }
}

Now you need create reqired instance of config depend on version of your file.

like image 44
Sergei Shvets Avatar answered Nov 02 '22 23:11

Sergei Shvets