Static classes and/or singletons -- How many does it take to become a code smell?
Posted
by
Earlz
on Programmers
See other posts from Programmers
or by Earlz
Published on 2011-04-17T03:22:36Z
Indexed on
2012/07/01
21:24 UTC
Read the original article
Hit count: 382
In my projects I use quite a lot of static classes. These are usually classes that naturally seem to fit into a single-instance type of thing. Many times I use static classes and recently I've started using some singletons.
How many of these does it take to become a code smell? For instance, in my recent project which has a lot of static classes is an Authentication library for ASP.Net.
I use a static class for a helper class that fixes ASP.Net error codes so it can be used like
CustomErrorsFixer.Fix(Context);
Or my authentication class itself is a static class
//in global.asax's begin_application
Authentication.SomeState="blah";
Authentication.SomeOption=true;
//etc
//in global.asax's begin_request
Authentication.Authenticate();
When are static or singleton classes bad to use? Am I doing it wrong, or am I just in a project that by definition has very little per-instance state associated with it?
The only per-instance state I have is stored in HttpContext.Current.Items
like so:
/// <summary>
/// The current user logged in for the HTTP request. If there is not a user logged in, this will be null.
/// </summary>
public static UserData CurrentUser{
get{
return HttpContext.Current.Items["fscauth_currentuser"] as UserData; //use HttpContext.Current as a little place to persist static data for this request
}
private set{
HttpContext.Current.Items["fscauth_currentuser"]=value;
}
}
© Programmers or respective owner