c-sharp
c-sharp

Reputation: 593

Any design pattern for the nested if statements?

Any design pattern to avoid the following nested if statements? I couldn't come up with any of the design patterns for this situation.

    private Message GetMessageFrom(string[] args)
    {
        string id = null, body = null, label = null, path = null;

        if (args.Length > 0)
        {
            id = args[0];
            if (args.Length > 1)
            {
                body = args[1];
                if (args.Length > 2)
                {
                    label = args[2];
                    if (args.Length > 3)
                        path = args[3];
                }
            }
        }

        return new Message(id, body, label, path);
    }

Upvotes: 0

Views: 225

Answers (2)

vkx
vkx

Reputation: 444

Similar to Tim's answer, with no loop, this might be an option :

string id = null, body = null, label = null, path = null; 

switch (args.Length) {
     case 4: path  = args[3]; goto case 3;
     case 3: label = args[2]; goto case 2;
     case 2: body  = args[1]; goto case 1;
     case 1: id    = args[0];
} 

I find it kinda ugly though :)

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460068

You could use ElementAtOrDefault which returns the default value(null in case of reference types like string) if the array doesn't contain this index:

string id    = args.ElementAtOrDefault(0);
string body  = args.ElementAtOrDefault(1);
string label = args.ElementAtOrDefault(2);
string path  = args.ElementAtOrDefault(3);
return new Message(id, body, label, path);

or you could use a for-loop and a switch:

string id = null, body = null, label = null, path = null;
for (int i = 0; i < args.Length; i++)
{
    switch (i)
    {
        case 0: id = args[i]; break;
        case 1: body = args[i]; break;
        case 2: label = args[i]; break;
        case 3: path = args[i]; break;
    }
}

Upvotes: 5

Related Questions