As per my knowledge, it is not advisable to use static variables in Web Applications. Now my question is, is it advisable to use static methods in web applications?is a static method use system memory as a static variable use? please clarify my doubt. Thanx in advance.
3 Answers
Yes, it is advisable to use static methods in a web application.
A static variable has very limited use in a web application, because all threads will share the same variable.
When it comes to methods, it's not a problem that all the threads access the same method, as the method itself won't change. The local data in a method is still separate for each call to the method, so several threads calling the same method at the same time is not a problem.
Generally speaking, if a method doesn't rely on any instance data, it should be static. I.e. if a method can be static (without any other chances to the method), it should be.
Comments
The reason you should avoid static variables is that they are often used to provide global state. This breaks encapsulation and makes maintaining and debugging programmes harder as any piece of code could change your variable.
In a threaded environment like ASP.NET this made worse by multiple threads potentially editing the same static variable's contents with non-deterministic results.
Static methods on the other hand can be a very good thing. They provide referential transparency which means the same inputs will always produce the same output and there's no side-effects changing state. This makes multi-threaded access much easier to reason about as threads cannot affect the processing of others by changing shared variables (assuming you're not using static variables of course).
It can also make unit testing easier and more robust as you don't need to test the underlying state of the world alongside your inputs and expected outputs.
it is not advisable to use static variables in Web Applications- why is that? What makes you say that? They can be useful, depending on usage scenario.