Domanda

When attempting to set default values for parameters that may exist in environment variables in JavaScript, I often see this pattern:

var lag;

try {
    lag = process.env.THROTTLE_LAG;
}
catch ( e ) {
    lag = 100;
}

I don't like it because, while it follows a common JavaScript pattern of declaring an empty variable for the purpose of later conditionally assigning it a value, the pattern of using try/catch as a logical branching stratagem seems kludgey. Examining technical factors, it tends to perform sub-optimally when compared with other branching strategies. Examining human factors, colleagues have argued that it lacks readability. Of course, opinions differ.

This shorter solution uses an empty catch block, which makes me cringe.

var lag = 100;

try {
    lag = process.env.THROTTLE_LAG;
}
catch ( e ) {}

(I'm open to the idea that my cringe is reflexive and not reflective of a real problem.)

È stato utile?

Soluzione

Using try/catch for logical branching is not recommended in general, but there are legitimate uses. One example, when you have to query a third party API, and there is no other way to access it. To keep you code more readable, you could encapsulate the try/catch in single, isolated function like

 function GetSomethingFromThirdPartyApi(parameter, defaultvalue)
 {
     try
     {
         return ThirdPartyApiCall(parameter);
     }
     catch(e)
     {
         return defaultvalue;
     }
 }

In my eyes this function is very clear and concise.

So I recommend to avoid cargo cults like "I have heard that [xyz] is bad, thus I never want to use it" and stay pragmatic - when cleaner alternatives cause more headaches than they prevent, use what works, dogmas don't solve problems.

However, in the given example, you can indeed solve your problem without the use of try catch, by a function like

function GetEnvironmentVar(varname, defaultvalue)
{
    var result = process.env[varname];
    if(result!=undefined)
        return result;
    else
        return defaultvalue;
}

now you can use it like

 var lag = GetEnvironmentVar("THROTTLE_LAG",100);

This is probably what you are looking for.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
scroll top