Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a class with only static methods be static? [closed]

Tags:

c#

static

I have a class with only static methods. Should the class itself be made static too? Does it matter?

like image 995
magnusarinell Avatar asked Apr 05 '16 11:04

magnusarinell


People also ask

Can a class have only static methods?

Utility Class, also known as Helper class, is a class, which contains just static methods, it is stateless and cannot be instantiated.

Why static methods are not recommended?

Static methods are bad for testability. Since static methods belong to the class and not a particular instance, mocking them becomes difficult and dangerous. Overriding a static method is not that simple for some languages.

When should static methods be used in class?

Since static methods cannot reference instance member variables, they are a good choice for methods that don't require any object state manipulation. When we use static methods for operations where the state is not managed, then method calling is more practical.

What are the rules for static methods?

Characteristics of Static MethodsA static method can call only other static methods; it cannot call a non-static method. A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables.


2 Answers

Does it matter?

Making a class static ensures that it can never be instantiated by generating a compiler error should the user attempt to do so. If the class, consisting of only static members, is simply not intended to be instantiated, there is no reason not to make it static. You can choose not to do so, but instances of such a class aren't going to be very useful, and users creating these instances are going to be left quite confused.

On the other hand, if you intend for instances of this class to be created but you expect derived classes to implement their own instance members, chances are that this class should be abstract, rather than static (and perhaps those instance members should be stated upfront via abstract definitions or an interface).

like image 133
BoltClock Avatar answered Oct 11 '22 19:10

BoltClock


In general: Yes.

You can prevent the programmer to create object instances of a certain class by making the class static. If this is what you intend, then do it. This prevents mistakes, by showing (other collegues, etc.) that the class is not intended to be instantiated.


public static class A 
{
  // Some static member
}

A a = new A(); // Compilation error
like image 39
Markus Weninger Avatar answered Oct 11 '22 20:10

Markus Weninger