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

14,409

Solution 1

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.

Solution 2

I would not make it a public static member of that class. The reason is that making it public static is saying something about the class' type: not only that "this type knows how to do this behavior", but also "it is the responsibility of this type to perform this behavior." And odds are the behavior no longer has any real relationship with the larger type.

That doesn't mean I wouldn't make it static at all, though. Ask yourself this: could the new method logically belong elsewhere? If you can answer "yes" to that, you probably do want to make it static (and move it as well). Even if that's not true, you could still make it static. Just don't mark it public.

As a matter of convenience, you could at least mark it internal. This typically avoids needing to move the method if you don't have easy access to a more appropriate type, but still leaves it accessible where needed in a way that it won't show up as part of the public interface to users of your class.

Solution 3

Not necessarily.

Moving public methods from static to non-static is a breaking change, and would require changes to all of your callers or consumers. If a method seems like an instance method, but happens to not use any instance members, I would suggest making it an instance method as a measure of future-proofing.

Solution 4

Yes. The reason "it can be static" is that it does not operate on the state of the object upon which it is called. Therefore it is not an instance method, but a class method. If it can do what it needs to do without ever accessing the data for the instance, then it should be static.

Solution 5

Yes, it should. There are various metrics of coupling that measure how your class depends on other things, like other classes, methods, etc. Making methods static is a way to keep the degree of coupling down, since you can be sure a static method does not reference any members.

Share:
14,409

Related videos on Youtube

Bernhard Hofmann
Author by

Bernhard Hofmann

Software Developer #SOreadytohelp

Updated on November 30, 2020

Comments

  • Bernhard Hofmann
    Bernhard Hofmann over 3 years

    Should C# methods that can be static be static?

    We were discussing this today and I'm kind of on the fence. Imagine you have a long method that you refactor a few lines out of. The new method probably takes a few local variables from the parent method and returns a value. This means it could be static.

    The question is: should it be static? It's not static by design or choice, simply by its nature in that it doesn't reference any instance values.

    • JasonTrue
      JasonTrue about 15 years
      Fairly exact duplicate of stackoverflow.com/questions/169378/…
    • Rinzler
      Rinzler over 14 years
      "fairly exact" is an oxymoron
    • Rebecca
      Rebecca over 12 years
      Resharper, the Visual Studio tool of tools, says yes! :-)
    • Robbie Dee
      Robbie Dee over 7 years
      @Junto Maybe in your version, but mine says can be made static...
  • Ray
    Ray about 15 years
    Yeah, but if someday you need to do this, you can always make it not static. Or am I missing something?
  • Michael
    Michael about 15 years
    @Ray - I cover this in my answer. static to non-static is a breaking change, so all the consumers need to be modified. Not a big deal for a small program, but if it is a library for consumption by others this has to be taken into account.
  • Abhishek
    Abhishek about 15 years
    I think he's mostly referring to private methods
  • Ray
    Ray about 15 years
    Sorry, you added that after my comment. In my mind I was thinking about private methods, but that's a valid point for public methods.
  • Michael
    Michael about 15 years
    @Ray - Right, this only applies to non-private members. I updated my answer to reflect this.
  • marc_s
    marc_s about 15 years
    My thoughts exactly - just because you could make something static doesn't mean you have to or should.....
  • Foredecker
    Foredecker about 15 years
    That is technically true, but not in a real material sense. The difference between static/non will very, very rarely be a factor in performance.
  • agnieszka
    agnieszka about 15 years
    ...or some day you can throw it out. these arguments are not good enough to for me to make a method nonstatic.
  • Ray
    Ray about 15 years
    Anyone have any references for this?
  • Not Sure
    Not Sure about 15 years
    -1: Textbook premature optimization. Speed should certainly not be the first criteria when deciding static vs. non-static for the general case.
  • Sandor Davidhazi
    Sandor Davidhazi about 15 years
    WRONG! "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." - Donald Knuth And this is very true also in this case. Please see Michael's answer.
  • Samuel
    Samuel about 15 years
    Agree with Not Sure, this should be your last reason to ever consider static vs not.
  • Ray
    Ray about 15 years
    So what would you do for private methods that could be made static?
  • Ashwin
    Ashwin about 15 years
    'just in case' is always a poor argument. It's a valid concern on a case-by-case basis, but not as a general rule.
  • agnieszka
    agnieszka about 15 years
    well if there is no special reason for leaving it nonstatic (and in this case as i understood there is not) then it is an argument
  • Scott Dorman
    Scott Dorman about 15 years
    @Not Sure: Sandor actually has most of the full quote and is correct. The compiler can perform certain optimizations on static methods that do make them faster to call.
  • Bernhard Hofmann
    Bernhard Hofmann about 15 years
    You can change your ReSharper settings :P
  • graffic
    graffic about 15 years
    The Math is a bad example. I guess it's better: newnumber = number.round(2) than newnumber = Math.round(number)
  • Prankster
    Prankster about 15 years
    If it were so easy we had no wornings from the Resharper... ever :)
  • Not Sure
    Not Sure about 15 years
    My point is speed is one of the poorest reasons you can have for deciding whether a function is static vs. non-static in 99% of cases. There are far more important considerations when it comes to OO design that other posts elaborate upon.
  • Victor Rodrigues
    Victor Rodrigues about 15 years
    Not necessarily. A static method will not access instance information, no members, like you said, but it is able to interact with other classes as well as another common method. Being static doesn't mean coupling is reduced, necessarily. However, I understood your point.
  • Sandor Davidhazi
    Sandor Davidhazi about 15 years
    @agnieszka: The special reason of generally using instance methods instead of static methods is state. If you leave you methods static, in a complex application you will introduce bugs that will make you tear your hair out. Think about modifying global state, race conditions, thread-safety etc.
  • Joel Coehoorn
    Joel Coehoorn about 15 years
    I wouldn't assume private static, either. The main thing is to ask yourself: does this method logically fit as part of this type, or is it just here as a matter of convenience? If the latter, might it fit better somewhere else?
  • supercat
    supercat over 13 years
    What if different customers are served by different branches? Mailing correspondence to the bank's main office may get it to the proper branch, eventually, but that doesn't mean that a customer wouldn't be better served by using the address of the particular branch that serves him.
  • SND
    SND almost 13 years
    Like: "could the new method logically belong elsewhere" - the clue is it doesn't rely on local state, perhaps the return type is where it belongs?
  • Jørgen Fogh
    Jørgen Fogh about 9 years
    A static method can still have access to state. It just gets the state from the object passed to it. Conversely, instance fields do not necessarily contain mutable state.
  • MakePeaceGreatAgain
    MakePeaceGreatAgain almost 7 years
    Instead static actualy increases coupling, because you are limited to exactly that static method, no way to iverride it for example and thus no way to change the behaviour.
  • FantomX1
    FantomX1 almost 4 years
    static methods can have their own static fields of the class, thus be with state. It is like what you say only if you keep such an agreement, not to make it stateful.