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.

The static keyword on a member in many languages mean that you shouldn't create an instance of that class to be able to have access to that member. However, I don't see any justification to make an entire class static. Why and when should I make a class static?

What benefits do I get from making a class static? I mean, after declaring a static class, one should still declare all members which he/she wants to have access to without instantiation, as static too.

This means that for example, Math class could be declared normal (not static), without affecting how developers code. In other words, making a class static or normal is kind of transparent to developers.

share|improve this question
    
If you are coding in Func Prog style a la Rich Hickey, this can be useful. –  Job Aug 26 '11 at 20:50
add comment

4 Answers

up vote 10 down vote accepted

It makes it obvious to users how the class is used. For instance, it would be complete nonsense to write the following code:

Math m = new Math();

C# doesn’t have to forbid this but since it serves no purpose, might as well tell the user that. Certain people (including me) adhere to the philosophy that programming languages (and APIs …) should be as restrictive as possible to make them hard to use wrong: the only allowed operations are then those that are meaningful and (hopefully) correct.

share|improve this answer
1  
I disagree with that philosophy. The problem I have is that needs change. So while it may have made sense to restrict it before now that restriction hinders our development for future needs. And the legacy library we are forced to use to interface with the old system (The one you wrote and sealed and staticed all of the classes) does not provide any way for us to extend or modify that code you wrote. Just because you had no reason to instantiate your class does not mean that I will not have a need for it in the future. While staticing a utility class makes sense, consider the future too. –  Chad Aug 26 '11 at 13:43
7  
@Chad Then the library is badly designed. Extending classes that were not designed for extension ultimately doesn’t work, so best make the class sealed in the first place. I acknowledge that not all people agree with this sentiment but the comments aren’t a good place to discuss this. But in the case of static this problem doesn’t even pose itself: instantiating System.Math will never make sense. –  Konrad Rudolph Aug 26 '11 at 13:46
    
@Konard, if you declare all the members of the Math class as static without declaring the Math class as static, still you can use it, without need for instantiation. –  Saeed Neamati Aug 26 '11 at 14:27
5  
@Saeed - This is true, but you could also instantiate the class, which doesn't serve any purpose. What do I do with an instance of the Math class? To explicitly show the intent of the class (no instantiation needed or wanted), it's marked static. –  Corbin March Aug 26 '11 at 14:37
1  
@Saeed Let’s turn this around: I propose you read my answer again since you seem to have misunderstood it: Your comments are unrelated to my answer. I never said that you need to write new Math(). –  Konrad Rudolph Aug 26 '11 at 14:59
show 4 more comments

StackOverflow has a great discussion on this topic. For ease of reference, I'll copy and paste it here, on behalf of its author, Mark S. Rasmussen:

I wrote my thoughts of static classes in an earlier thread:

I used to love utility classes filled up with static methods. They made a great consolidation of helper methods that would otherwise lie around causing redundancy and maintenance hell. They're very easy to use, no instantiation, no disposal, just fire'n'forget. I guess this was my first unwitting attempt at creating a service oriented architecture - lots of stateless services that just did their job and nothing else. As a system grows however, dragons be coming.

Polymorphism

Say we have the method UtilityClass.SomeMethod that happily buzzes along. Suddenly we need to change the functionality slightly. Most of the functionality is the same, but we have to change a couple of parts nonetheless. Had it not been a static method, we could make a derivate class and change the method contents as needed. As it's a static method, we can't. Sure, if we just need to add functionality either before or after the old method, we can create a new class and call the old one inside of it - but that's just gross.

Interface woes

Static methods cannot be defined through interfaces for logic reasons. And since we can't override static methods, static classes are useless when we need to pass them around by their interface. This renders us unable to use static classes as part of a strategy pattern. We might patch some issues up by passing delegates instead of interfaces.

Testing

This basically goes hand in hand with the interface woes mentioned above. As our ability of interchanging implementations is very limited, we'll also have trouble replacing production code with test code. Again, we can wrap them up but it'll require us to change large parts of our code just to be able to accept wrappers instead of the actual objects.

Fosters blobs

As static methods are usually used as utility methods and utility methods usually will have different purposes, we'll quickly end up with a large class filled up with non-coherent functionality - ideally, each class should have a single purpose within the system. I'd much rather have a five times the classes as long as their purposes are well defined.

Parameter creep

To begin with, that little cute and innocent static method might take a single parameter. As functionality grows, a couple of new parameters are added. Soon further parameters are added that are optional, so we create overloads of the method (or just add default values, in languages that support them). Before long, we have a method that takes 10 parameters. Only the first three are really required, parameters 4-7 are optional. But if parameter 6 is specified, 7-9 are required to be filled in as well... Had we created a class with the single purpose of doing what this static method did, we could solve this by taking in the required parameters in the constructor, and allowing the user to set optional values through properties, or methods to set multiple interdependent values at the same time. Also, if a method has grown to this amount of complexity, it most likely needs to be in its own class anyways.

Demanding consumers to create an instance of classes for no reason

One of the most common arguments is, why demand that consumers of our class create an instance for invoking this single method, while having no use for the instance afterwards? Creating an instance of a class is a very very cheap operation in most languages, so speed is not an issue. Adding an extra line of code to the consumer is a low cost for laying the foundation of a much more maintainable solution in the future. And finally, if you want to avoid creating instances, simply create a singleton wrapper of your class that allows for easy reuse - although this does make the requirement that your class is stateless. If it's not stateless, you can still create static wrapper methods that handle everything, while still giving you all the benefits in the long run. Finally, you could also make a class that hides the instantiation as if it was a singleton: MyWrapper.Instance is a property that just returns new MyClass();

Only a Sith deals in absolutes

Of course, there are exceptions to my dislike of static methods. True utility classes that do not pose any risk to bloat are excellent cases for static methods - System.Convert as an example. If your project is a one-off with no requirements for future maintenance, the overall architecture really isn't very important - static or non static, doesn't really matter - development speed does, however.

Standards, standards, standards!

Using instance methods does not inhibit you from also using static methods, and vice versa. As long as there's reasoning behind the differentiation and it's standardised. There's nothing worse than looking over a business layer sprawling with different implementation methods.

share|improve this answer
4  
Hmmm, don't know that I'd copy and paste an entire answer here. Maybe link and paraphrase, include an alternative viewpoint since you mention a "discussion", share your own experience? –  Corbin March Aug 26 '11 at 14:59
    
"Only a Sith deals in absolutes" - I hadn't seen that used like that before.... but it's PERFECT. Made me lol. –  Brook Aug 26 '11 at 19:40
2  
@Corbin: Mark had a great answer. I gave him credit and I copy/pasted for ease of reference. My own views on this matter match Mark's. I don't see the point of your comment, other than to start debate. –  Rick Aug 27 '11 at 18:16
1  
@Rick: The copied answer is quite long, and paraphrasing it would definitely help. Just a sentence like "It's not just that they aren't really useful, they can even harm, as this SO post shows:" would let me quickly skip over it as I see it's not the information I was looking for. –  blubb Aug 27 '11 at 21:04
    
@Simon: LOL I 1+'ed your post. In an attempt to quit arguing over something so stupid, I'll just agree. :) Hopefully the original poster found my reply/copy and paste useful. –  Rick Aug 28 '11 at 20:35
add comment

I'm surprised noone else has mentioned this: static classes allow for extension methods - safely extending an existing type (including adding method definitions to interfaces) that you don't own. For instance, what in Scala is

trait MyFoo {
  def foo: Int
  def plusFoo(a: Int) = foo + a
}

may be expressed in C# as

public interface IMyFoo {
  int Foo();
}

public static class MyFooExtensions {
  public static int PlusFoo(this IMyFoo f, int a) {
    return f.Foo() + a;
  }
}
share|improve this answer
    
you found needle in the haystack. +1 –  Saeed Neamati Aug 27 '11 at 16:35
add comment

For me, a static class (in C#) is kind of like calling out a function.

For example

public static string DoSomething(string DoSomethingWithThisString){}

I pass in a string and get back a string. Everything is contained in that method. No access to member variable, etc.

Honestly, mostly its use for me has been to lessen the lines of code:

Why do:

MyClass class = new MyClass();
String s = class.DoSomething("test");

When I can do this:

String s = MyClass.DoSomething("test");

So, I would use static classes in those cases, when I wanted to do something without the need for a class and would mean less typing.

Mark S. points are valid, but for me if I have some utility methods its just easier to pretend I'm calling a function to reference them as one liners.

That may be simplistic, but that's mostly how I have used static.

share|improve this answer
    
new MyClass().DoSomething("test") is still valid. I use this a lot for Test Data Builders. –  JoanComasFdz Mar 4 at 7:24
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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