Method Can Be Made Static, But Should It

Method can be made static, but should it?

Static methods versus Instance methods


Static and instance members of the C# Language Specification explains the difference. Generally, static methods can provide a very small performance enhancement over instance methods, but only in somewhat extreme situations (see this answer for some more details on that).

Rule CA1822 in FxCop or Code Analysis states:

"After [marking members as static], the compiler will emit non-virtual call sites to these members which will prevent a check at
runtime for each call that ensures the current object pointer is
non-null. This can result in a measurable performance gain for
performance-sensitive code. In some cases, the failure to access the
current object instance represents a correctness issue."

Utility Class

You shouldn't move them to a utility class unless it makes sense in your design. If the static method relates to a particular type, like a ToRadians(double degrees) method relates to a class representing angles, it makes sense for that method to exist as a static member of that type (note, this is a convoluted example for the purposes of demonstration).

Should C# methods that *can* be static be static?

It depends.
There are really 2 types of static methods:

  1. Methods that are static because they CAN be
  2. Methods that are static because they HAVE to be

In a small to medium size code base you can really treat the two methods interchangeably.

If you have a method that is in the first category (can-be-static), and you need to change it to access class state, it's relatively straight forward to figure out if it's possible to turn the static method into a instance method.

In a large code base, however, the sheer number of call sites might make searching to see if it's possible to convert a static method to a non static one too costly. Many times people will see the number of calls, and say "ok... I better not change this method, but instead create a new one that does what I need".

That can result in either:

  1. A lot of code duplication
  2. An explosion in the number of method arguments

Both of those things are bad.

So, my advice would be that if you have a code base over 200K LOC, that I would only make methods static if they are must-be-static methods.

The refactoring from non-static to static is relatively easy (just add a keyword), so if you want to make a can-be-static into an actual static later (when you need it's functionality outside of an instance) then you can. However, the inverse refactoring, turning a can-be-static into a instance method is MUCH more expensive.

With large code bases it's better to error on the side of ease of extension, rather than on the side of idealogical purity.

So, for big projects don't make things static unless you need them to be. For small projects, just do what ever you like best.

Should make static method when possible?

You don't make methods static just when possible, you do it when it makes sense, ie. what method does is not related to specific instance, but to a class in general.

Evaluate whether this is the case here, but you are not using current instance anywhere in the method, so above might be the case.

Should class methods be made static in all cases if they don't use absolutely any class fields?

If a method doesn't use any instance variables in it's containing class then it doesn't have to be static, but it should be. As a general rule, if a method doesn't require a class instantiation to be used then it should be extracted to a utility class/interface as a static method.

ReSharper complains when method can be static, but isn't

I find that comment very useful as it points out two important things:

  1. It makes me ask myself if the method
    in question should actually be part
    of the type or not. Since it doesn't use
    any instance data, you should at
    least consider if it could be moved
    to its own type. Is it an integral part
    of the type, or is it really a general
    purpose utility method?

  2. If it does make sense to keep the
    method on the specific type, there's
    a potential performance gain as the
    compiler will emit different code
    for a static method.

Should I make my private class methods static?

If the methods don't access any of the type's state then they should be static.

Static method calls provide a performance gain over instance methods and the presence of a static method tells future readers of your code that calling this method will create no side effects in the the state of the current instance of the type.

The performance gain of a static method comes from the fact that the compiler does not have to emit callvirt instructions to call a static method. The callvirt instruction is handy for instance calls in that it does a null check prior to calling the method. However, when you call a static methods there is no need to check for null so the compiler is free to emit the faster call instruction which doesn't check for null.

Should I always make my methods static where possible?

Static isn't evil. Static is evil if used incorrectly, like many parts of our programming toolkit.

Static can be very advantageous. As the accepted answer here points out, static can have a potential speed improvement.

As a general rule if the method isn't using any fields of the class then its a good time to evaluate its function, however ultimately utility methods that can be called without instantiating an object can often be useful. For instance the DirectoryInformation and FileInformation classes contain useful static methods.

Edit

Feel obligated to point out that it does make mocking a lot harder but it is still definitely testable.

It just means you need to think harder about where static methods go, so that you can always test them without needing to rely on a mock/stub. (ie: don't put them on your DTO that requires a persistent connection to the database).

Good reasons for static methods?

By defining a method static, so a procedure that computes something, you manifest an intent to a consumer of your API about statelessness of your function.

When we use static function, we do not expect it saves a state of computation or some computed internal value somewhere in it's internal static private variables, so the next call to that function may have different result even with the same parameters passed during the first call.

In short: whenever you see a function that just executes an action over parameter and not preserve some state, it is a good candidate for making it static.



Related Topics



Leave a reply



Submit