I just got a project that have some core classes that uses static methods.
It is a C# project, with an interface that reflects some methods to javascript.
In this interface, there are a lot of calls to static methods that uses HttpContext and get data from database (actually just one access database), such as this (some methods have some logic inside):
public static string UsrId {
get{
try {
return HttpContext.Current.Session["usrid"].ToString();
} catch(NullReferenceException) {
return ServiceVars.GuestId;
}
}
}
So my question is:
Is this a bad pratice? What are the cons (and pros?) of doing this?
I read somewhere that static methods that uses database connections are bad for high traffic sites, because it would queue up the requests. Is this true? Or should I not worry about database connection in static methods?
And what about the HttpContext inside static methods, is it bad and why?
What’s bad here is the catch of
NullReferenceException. Don’t ever do that.Instead, check for null first:
Also, the problem you may be referring to isn’t a problem with static methods, or with
HttpContext. It’s a problem with usingSessionstate.