Static vs instanced class

Duplicate

Should static static methods be C #?


Please forgive me if this question seems trivial - I am looking at some source code that otherwise looks good, but it raised some questions ...

If a given class has no data members, that is, it does not maintain any state, is there any advantage to not labeling this class as a static class with static methods?

Are there any benefits to unlabelled methods that don't store state as static?

Thanks!

EDIT: Since someone brought up this, the code I'm looking for is written in C #.

+1


a source to share


4 answers


Yes. I can think of some reasons:



  • Simple mocking and unit testing
  • Easy to add state
  • You can pass it (like interface

    or something else)
+8


a source


I would say there is an advantage in making them static methods of the class as well as making the class abstract. Thus, it is clear to the programmer that this class was never intended to be instantiated and the methods are still available.



+2


a source


It can be useful to leave methods that do not change state not static if you intend (or think you can intend) to inherit from a class and override those methods with code that changes state. Although in this case it really should be an abstract class.

+2


a source


If a class doesn't maintain any state, doesn't have any instance methods, and can be fully implemented using the class's methods, I usually take a long time to see if its behavior would actually be more useful elsewhere. I believe they usually have many methods on strings doSomethingWithItem(Item item)

, which would make more sense as an instance method in Item

.

Yes, I know this does not answer your question, but I think others have already understood this well and I wanted to get another perspective.

+2


a source







All Articles