The static
modifier means that the type cannot be instantiated or a member cannot be associated with an instance. But whats the benefit of this restriction on instantiation and under what use case scenario should types/members be declared static ?
views:
125answers:
5Types are declared static to define, that no instances of this type can be created (and can only contain static data).
Methods are defined static in a non-static class when they do not reference the internal data of a class. This is sometimes important to know when reading or using code.
But whats the benefit of this restriction on instantiation and under what use case scenario should types/members be declared static ?
For members, when you have state that belongs to the class (or should be shared among all instances of the class) or methods that don't depend on instance-level state.
For types, when you have a bag of methods that aren't dependent on instance-level state (for example, System.Math
) including extension methods.
Several benefits:
- Uses less memory as object doesn't need to be instantiated to call a method
- Allows global access to a property / member (although threading issues need to be considered)
- Indicates to the caller that the method is an aspect of the class rather than the object instance which has implications with regards to OOP.
Types should be declared as static when you want the compiler to inhibit the instantiation of instances of the type, and prevent the additional of any non-static (instance based) members. All this does is guarantee that you won't inadvertently add a non-static member later.
Members of a non-static class should be declared as static If and Only If the member does not reference any instance-based state of the object, (directly, or indirectly through another non-static member). They cannot reference any non-static member of the type, but non-static members can reference them.
I go by the following principles.
Declare static if:
- You need static access (beware of this though since it creates Very hard dependencies), i usually only allow static access for Inversion of Control accessors and simple functionality helpers (such as System.Math)
- You absolutely doesn't want your class to be instantiated and should only exist as one single instance (singleton) such as in the above case of a helper or IoC container
Don't declare static if:
- There is any chance of concurrency issues. Private readonly value -instances can only be read and are as such practically readonly so these are fine as static constant-a-like members but otherwise be wary.
- There exists dependencies outside the class, ie something else uses the member or the member uses something else outside the type. This makes testing a pain.
So mainly, increase cohesion decrease coupling, otherwise you´re fine using static instances.