views:

366

answers:

4

Duplicate

Should C# methods that can be static be static?


Please forgive me if this question seems elementary - I'm looking over some source code that otherwise looks pretty good, but it's raised some questions...

If a given class has no member data - i.e. it doesn't maintain any sort of state, are there any benefits in not marking that class as a static class with static methods?

Are there any benefits in not marking methods which don't maintain state as static?

Thanks!

EDIT: Since someone brought it up, the code I'm looking at is written in c#.

+8  A: 

Yes. I can think of some reasons:

  1. Ease of mocking and unit testing
  2. Ease of adding state
  3. You could pass it around (as an interface or something)
Mehrdad Afshari
4. Overriding implementation.
Mark
+2  A: 

I would say there is a benefit to making them static methods of the class, and on top of that making the class abstract. That way, it's clear to the programmer that this class was never intended to be instantiated and the methods are still available.

Mike Caron
+2  A: 

There might be a benefit in leaving methods that don't change state non-static, if you intend (or think you might intend) to inherit from the class and override those methods with code that does change state. Though in that case it really should be an abstract class.

MattK
There is obviously no case for making the class abstract if you will need to instantiate the object.
Tetsujin no Oni
You still need to use instance types/methods to inherit even if the derived type has no intent on maintaining state since you cannot inherit from static classes or override static methods.
Mark
Agreed. Though philosophically, at least, there's no reason to instantiate an object that holds no state.
MattK
+2  A: 

If a class doesn't maintain any state, doesn't have any instance methods, and could be implemented entirely with class methods, I usually take a long hard look at whether its behaviors would in fact make more sense somewhere else. I find they usually seem to have a lot of methods along the lines of doSomethingWithItem(Item item), which would make more sense as an instance method in Item.

Yeah, I know this doesn't answer your question, but I think others have covered that pretty well already, and I wanted to get another perspective out there.

Adam Jaskiewicz
Preach on, brother Adam
Jim Arnold