Should C# Methods That *Can* Be Static Be Static

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 a class with only static methods be static?

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).

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 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 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.

Should I use static function in c# where many calls the same func?

Sounds like there could be a problem. Calling a method which operates on static (shared) objects in a multithread environment should ring some alert bells for you.

Review your code and if there's a chance that a shared object is accessed from two (or more) threads at the same time, make the object an instance field and make your methods instance methods.

Of course, whether or not there is a risk depends much on the actual code (which you don't show) but making all calls nonstatic means that you lower the potential risk.

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.



Related Topics



Leave a reply



Submit