Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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;
        }
    }
share|improve this question
    
It might seem that in a RESTful application, static classes are a natural fit. However, this kind of architecture can be very limiting, and it also appears that you are using static classes to store global variables. You might as well be using a non-OO language. –  Matt H Apr 17 '11 at 6:57
    
It takes anywhere between one and infinity, depending on who you ask. –  Bart van Ingen Schenau Apr 16 at 9:18
add comment

put on hold as primarily opinion-based by gnat, Bart van Ingen Schenau, MichaelT, GlenH7, Kilian Foth Apr 17 at 11:00

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise.If this question can be reworded to fit the rules in the help center, please edit the question.

6 Answers

As byte points out, singletons are often overused. However, they are often over-used because they are used where a static instance would be better. From your question you seem to be implying they are the same thing or are interchangeable. They are not the same, and although they can be interchangable in some cases there is usually agood reason to prefer one over the other.

I don't think any specific number of statics or singleton's is bad, there may be some cases where you use a lot of one or the other, some case where you do not.

I think the things to consider and ask youself are, does X need to be a singleton, can it be a static. Usually if something needs to live and be accessed for the entire lifetime of it's scope then it should be a static, if it is something that may never be accessed, may be costly to create and you only ever need one then a singleton is better.

share|improve this answer
    
The only time I use singletons instead of a static class is in cases where I need to inherit from something, or I want a class to be capable of being inherited from. –  Earlz Apr 17 '11 at 16:24
add comment

In the case of singletons the answer is one - because a singleton is a global variable. Sure, it's dressed up to smell a lot nicer than a traditional global variable, and sure, it offers advantages (such as private scoping) that traditional global variables don't have, but a global variable is still what it is.

share|improve this answer
add comment

I dont believe there is some kind of limit on the number of singletons there are. In my current project nearly all classes are singletons( 30 and growing). And they interact with each other in a provider-consumer mode. Has worked fine for over a year. The trick is making sure there is little direct coupling between them, and you call them only when you need the service. A little juglery is sometimes necessary, in situations such as the application startup. But works well for me.

share|improve this answer
add comment

There's no threshold number or percentage that would cause the code to suddenly smell. It all depends on your requirements.

For example, if your requirement was to build a class library that implemented several math functions like sin, cosine and abs, your ratio of static to non-static methods might be close to 100%.

Singletons are discouraged for a number of reasons, which are easily Googled. As with all patterns, you should restrict its use to that which is appropriate. But again, there's no target threshold, above which it begins to smell. If your requirement is to build a global configuration system, or some such thing, again: your percentage of singleton to non-singleton classes might be close to 100%.

share|improve this answer
add comment

The reason they are often a code smell is that a Singleton is to create a global. If you require a state to be global to the application and stored for the life of the application, then Singletons might be a good idea. The main problem, is that you are removing the ability for the programmer to decide whether they want the state to be global or temporary.

The reason static methods are often a code smell is that they are often used to namespace functions. The problem is static methods make it extremely difficult to unit test, to extend and replace functionality. If I want to use my class, I have to go through the entire source code and replace every reference to your call to the static method. If I don't have your source code, well, I either deal with it, use another library or rewrite all classes that reference the static method.

As you can tell, static methods can be more than a code smell, they can be downright fight against productivity. If the library is only going to be used by the author, then it doesn't really matter in the end.

share|improve this answer
add comment

Static classes almost always a bad smell because they make unit testing hard. You can't make mock or make test versions of a static class. If any of your code is a client of a static class, then there is tight coupling between the two classes.

Instead of static classes, you should be using a normal object but manage it with an Inversion of Control container.

share|improve this answer
    
why do you recommend Inversion of Control container? –  gnat Apr 16 at 9:16
    
@gnat, that's a very broad question. Do mean why use an IoC container specifically, or why use a dependency injection style in general? –  Dangph Apr 17 at 0:41
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.