开发者

Is it bad practice to change the value of a static variable?

I have a static string variable which i need to change possibly depending on the HTTP protocol.

Is it bad practice to change the static string variable>

static string QuoteWebServiceUrl = CommonFunctions.ReadAppSettin开发者_如何学Cg("QuoteWebServiceUrl");

if(url == "https")
{
  QuoteWebServiceUrl = CommonFunctions.ReadAppSetting("QuoteWebServiceUrlSecure");
}
else
{
  QuoteWebServiceUrl = CommonFunctions.ReadAppSetting("QuoteWebServiceUrl");
}

Thanks


No. Of course you can change the value of a static string variable. Why do you think it's a bad pratice?


I mean, modifying a static variable is a non-issue. It's a variable. It can vary. So why would varying (i.e., modifying it) be a bad practice? Yes, there are situations where you shouldn't or have to be careful if you do, but in general, it's not.

The big issue here is reading application settings deep in the guts of your application. It kills maintainability and testability. It is a horrifically bad practice and I encourage you to stop immediately.


In this case it looks like it's just a one-time setup, but you must be mindful of race conditions in a multithreaded environment, including ASP.NET.


Programmatically speaking, from the language POV it's ok to change it.

Otherwise depends on the logic of the variable, the meaning it has in the overall business logic.


On its own, changing a static variable is not a bad thing.

However, I see no precautions taken regarding multiple instances of this class modifying the same static. This is a potential concurrency issue.

In addition, you should probably set the two settings in statics and choose the one that's appropriate based on your condition, but leave the statics alone once they are initialized.


For multi-thread editing static variable is not good not scalable and can run in some random cases inappropriately. but......

There are some business logic where there is only one thread at a time to process or restricting to one thread. If that's the case its completely OK to use.

In those cases it is good to have and we may sometimes have no other options rather changing (one of the case is with when using WEBAPI with Async task and most importantly only one thread at time and user wants dynamic status update for each api hit)


You can use static property instead of static variable.


private static string QuoteWebServiceUrl 
{ 
    get 
    { 
        if(url == "https") 
        {   
            return CommonFunctions.ReadAppSetting("QuoteWebServiceUrlSecure"); 
        } 
        else 
        {   
            return CommonFunctions.ReadAppSetting("QuoteWebServiceUrl"); 
        } 
    } 
}

Static Property


No, it is not a bad practice in general. In your particular case, it is a terrible idea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜