When is it best to use static functions in ASP.NET?
I have been wondering, when to use static functions, and when not to in ASP.NET?
What are the advantages and disadvantages in using th开发者_运维知识库em, in various aspects like performance, following good practices etc (and many more, whichever you feel is relevant).
Cons:
- threading issues (static functions don't require an instance to be called on, so it is easy to invoke them from different parts of the code and if they read/write to a shared state this state might be corrupted in a multi-threaded environment such as ASP.NET)
- difficult to unit test (as static functions don't require an object instance, constructor injection is impossible meaning that the only way to inject dependencies is by passing them as arguments to the function itself)
Pros:
- performance (this is questionable - in most cases performance gains will be completely negligible compared to other parts of the code)
There are definitely situations where static is the appropriate solution, as with any application. Any time you have some object that ought to live at the application scope, and not at the request scope, it should be static and you should use static methods to access and manipulate it.
As an example, here's a snippet of code I wrote recently for an ASP.NET application, which is essentially a serializer cache. Serializers are expensive to create and we can reuse the same one per type for as long as our application lives, so there's no need to waste time in each request thread for them:
(Note: this has been stripped down to demonstrate the static aspects)
public class XmlSerializerUtility
{
private static Dictionary<Type, XmlSerializer> serializers = new Dictionary<Type, XmlSerializer>();
private static object sync = new object();
public static T Deserialize<T>(string input)
{
XmlSerializer xs = GetSerializer(typeof(T));
using (StringReader sr = new StringReader(input))
{
return (T)xs.Deserialize(sr);
}
}
public static XmlDocument Serialize(object input)
{
XmlDocument doc = new XmlDocument();
XmlSerializer xs = GetSerializer(input.GetType());
using (MemoryStream stream = new MemoryStream())
{
xs.Serialize(stream, input);
stream.Position = 0;
doc.Load(stream);
}
return doc;
}
private static XmlSerializer GetSerializer(Type type)
{
lock (sync)
{
XmlSerializer xs = null;
if (!serializers.ContainsKey(type))
{
xs = new XmlSerializer(type);
serializers.Add(type, xs);
}
else
{
xs = serializers[type];
}
return xs;
}
}
}
The only major disadvantage to a static method is that it's almost entirely non-unit testable. Users of the method have to bind to the concrete method and cannot bind to an abstraction, thus making faking or mocking difficult if not impossible.
This may or may not be an issue, depending on the code, however.
The other thing you want to watch out for is that static data is universal across all requests to the server.
精彩评论