Programming Practices – Is Using Switch Case to Set Environment Bad Practice?

configuration-managementprogramming practicesprogramming-languagesrouting

In the last three years that I have worked as developer, I have seen a lot of examples where people use a switch statement to set the path (both in back-end and front-end) for a URL. Below is an example of this:

Back-end example (C#):

public static string getHost(EnvironmentEnum environment){
    var path = String.Empty;
    switch (environment)
    {
        case EnvironmentEnum.dev:
            path = "http://localhost:55793/";
            break;
        case EnvironmentEnum.uat:
            path = "http://dev.yourpath.com/";
            break;
        case EnvironmentEnum.production:
            path = "http://yourpath.com/";
            break;
    }
    return path;
}

Front-end example (JavaScript):

(function () {
    if (window.location.host.indexOf("localhost") !== -1) {
        window.serviceUrl = "http://localhost:57939/";
    }
    else if (window.location.host.indexOf("qa") !== -1) {
        window.serviceUrl = "http://dev.yourpath.com/";
    }
    else {
        window.serviceUrl = "http://yourpath.com/";
    }
})();

It has been discussed whether it is a good or bad practice, and I think it is a bad practice, because we must avoid this kind of code and set a proper configuration. But to be honest I really don't know the proper answer and why is it not recommended and what is the correct way to implement this.

can someone explain it the pros and cons of the above practice?

Best Answer

Code that works for you and is easy to maintain is by definition "good". You should never change things just for the sake of obeying someone's idea of "good practice" if that person cannot point out what the problem with your code is.

In this case, the most obvious problem is that resources are hard-coded into your application - even if they're selected dynamically, they're still hard-coded. This means that you cannot change these resources without recompiling/redeploying your application. With an external configuration file, you'd only have to change that file and restart/reload your application.

Whether or not that is a problem depends on what you do with it. In a Javascript framework that is automatically redistributed with every request anyway, it is no problem at all - the changed value will propagate to every user the next time they use the application. With an on-premises deployment in a compiled language in an inaccessible location it is a very big problem indeed. Reinstalling the application might take a long time, cost a lot of money or have to be done at night to preserve availability.

Whether or not hard-coded values are a problem depends on whether your situation is more like the first example or more like the second example.

Related Topic