Thursday, August 4, 2011

Nested conditional statement other than switch case in C#, C++, Java, PHP, JavaScript

nested-conditional-statement


Switch statements are nice, sometimes we need to just return some value based on an input variable. For example in our case I needed to get the key field of an LDAP object class we preferred to use in our software. So I had a simple C# function which went something like this


public static string getKeyByObjectClass(string strObjectClass){
switch(strObjectClass){
    case "user":
    return "samAccountName";
    case "user-mailbox":
    return "samAccountName";
    case "user-mail":
    return "samAccountName";
    case "contact":
    return "CN";
    case "contact-mail":
    return "CN";
    case "group":
    return "samAccountName";
    default:
    return "";
 }
}

I thought it is possible to simplify this switch statement with a nested conditional statement. And following was the result of some deliberation ;)








public static string getKeyByObjectClass(string strObjectClass){
              return (strObjectClass == "user") ? "samAccountName" : (strObjectClass == "user-mailbox") ?"samAccountName" :(strObjectClass == "user-mail") ? "samAccountName" : (strObjectClass == "contact") ? "CN" :(strObjectClass == "contact-mail") ? "CN" : (strObjectClass == "group") ? "samAccountName" : "";

You can definitely use || operator, minimize the code, and refine the crude version of nested conditional statement we created earlier, let's just do that

public static string getKeyByObjectClass(string strObjectClass){
              return (strObjectClass == "user" || strObjectClass == "user-mailbox" || strObjectClass == "user-mail") ? "samAccountName" :                                      (strObjectClass == "contact" || strObjectClass == "contact-mail" ) ? "CN" : "";
}

But now we definitely have some compromise on flexibility, maybe we'll want to use a different key for an object class say "user-mail" and then we'll have to modify this code in tiny bit different way(maintenance hell anyone?) ;)
I'm sure many intelligent folks have already done this or even a better variation but I also know that there are dumb guys and gals just like me out there who would most probably yell "Eurika!!!" on understanding the magic of nested conditional statements.
Its not just and only C# stuff, in fact the code will work with JavaScript, PHP, Java, C++ and many others with little or no variation.