47

I have read the following discussions:

Should private helper methods be static if they can be static , and
Should all methods be static if their class has no member variables

It seems that people in general would accept static methods, but are a little bit skeptical about it, for the following 2 reasons:

  1. They are hard to test.
  2. They violate the OO principle. (They are functions, not methods, said a person.)

And the most acceptable static methods are private static ones. But then why do static methods exist at all, and in what situations they are the first priority to be adopted?

1

11 Answers 11

75

Static methods aren't hard to test in and of themselves. The problem is that other code calling the static method is hard to test, because you can't replace the static methods.

I think static methods are fine either when they're private or when they're "utility" methods - e.g. to do string escaping. The problem comes when you use static methods for things that you want to be able to mock out or otherwise replace within tests. Factory methods can be useful too, although dependency injection is generally a better approach - again, it partly depends on whether you want to be able to replace the functionality in tests.

As for not being "OO" - not everything you write in a generally OO language has to be "pure" OO. Sometimes the non-OO route is simply more pragmatic and leads to simpler code. Eric Lippert has a great blog post about this, which unfortunately I can't find right now. However, there's a comment in this post which is relevant. It talks about extension methods rather than static methods, but the principle is the same.

Extension methods are often criticized as being "not OOP enough". This seems to me to be putting the cart in front of the horse. The purpose of OOP is to provide guidelines for the structuring of large software projects written by teams of people who do not need to know the internal details of each other's work in order to be productive. The purpose of C# is to be a useful programming language that enables our customers to be productive on our platforms. Clearly OOP is both useful and popular, and we've therefore tried to make it easy to program in an OOP style in C#. But the purpose of C# is not "to be an OOP language". We evaluate features based on whether they are useful to our customers, not based on whether they conform strictly to some abstract academic ideal of what makes a language object-oriented. We'll happily take ideas from oo, functional, procedural, imperative, declarative, whatever, so long as we can make a consistent, useful product that benefits our customers.

3
  • Thanks. Great explanations. So you think utility method is a good practice, right? But then I don't understand why people would use static other then "private" or "utility" though. Basically, I use utility methods a lot. Oct 7, 2009 at 9:01
  • 3
    Well, it's any time that you write a method which is logically to do with the type rather than an instance of the type. In some areas this is common; in others it's rare.
    – Jon Skeet
    Oct 7, 2009 at 9:19
  • In the first instance, I didn't understand that static methods can't be replaced. After some research I realised that in testing is difficult, if not impossible, to replace them with mocks. Oct 3, 2019 at 9:04
22

I'd say that static methods are definitely OK when they are functions, i.e. they don't do any IO, don't have any internal state and only use their parameters to compute their return value.

I'd also extend this to methods that change the state of their parameters, though if this is done excessively, the static method should properly be an instance method of the parameter class that it mainly operates on.

7

Think of this for a moment. In OO coding, every single function call actually looks like this:

method(object this, object arg1, object arg2) where this is the object you are calling. All it really is is syntax sugar for this. Additionally it allows you to clearly define scope of variables because you have object variables etc.

Static methods simply don't have a "this" parameter. Ie you pass variables in and possibly get a result back out. 1.) is the main reason people avoid them, you can't create an interface to a static method (yet) so you can't mock out the static method to test it.

Secondly OO are procedures functions etc. Static methods make a lot of sense in certain situations, but they can always be made into a method on an object.

Mind you, you couldn't remove this without a hack:

static void Main(string[] args)
{
}

The code that starts your application MUST be callable WITHOUT a reference to an object. So they give you flexibility, whether you choose to use them in your scenario will be predicated by your requirements.

1
  • 1
    "you can't create an interface to a static method (yet)" 10 years later, still waiting...
    – Big_Bad_E
    Mar 24, 2020 at 22:24
5

Static methods are fine in most situations where the singleton pattern gives too much flexibility.

For example, take a simple utility such as raising a primitive to a power - obviously you never need to have any polymorphism in that. Primitive values are of static type and mathematical operations are well defined and don't change. It's not like you'll ever get the situation of having two different implementations an no way of switching between them without rewriting all your client code.


(irony off )

Modern JVMs are pretty good at inlining small calls if only one implementation of an interface is loaded. Unless you have profiled your code and know dispatching your utilities to an interface is an overhead, you've no excuse for not making your utility methods into an interface which can be varied if required.

3

Another good scenario for static methods are implementations of the Factory pattern, where you are allowing for instances of a class to be constructed in a specific manner.

Consider the Calendar class, which has a set of static getInstance methods, each returning instances primed with the desired TimeZone and/or Locale or the default.

1
  • I don't use dependency injection nor (often) mock objects for testing but static methods implementing factory would make mocking impossible, no? Oct 7, 2009 at 9:34
3

I think a definite case for static methods is when you cannot make them dynamic, because you cannot modify the class.

This is typical for JDK objects, and also all objects coming from external libraries, and also primitive types.

2

I often use static factory methods instead of or in conjunction with public constructors.

I do this, when i need a constructor that does something you would not expect a constructor to do. I.e. load settings from a file or database.

This approach also provides the possibility of naming the "constructors", based on what they do. This is especially useful, when the parameters themselves are not enough to figure out what happens in a constructor.

Sun uses this approach in

Class.forName("java.lang.Integer");

and

Boolean.valueOf("true");
1

First of all, you can't dismiss static-methods there is a reason people still use it.

  1. some design patterns are based on static methods, singleton for example:

    Config.GetInstance();

  2. Helper functions, lets say you have a byte-stream and you want a function to convert it into a string of Hex numbers.

there are many uses for static-methods, saying that does not mean that some people abuse it too much(Code Review is best option when people abuse code).

1

Util classes can be OK to be static. As in someone elses example above, with escaping strings. The problem lies when those utils classes perform functions that we would want to mock. For example, the FileUtils class in apache commons - it is often the case that I want to mock file interactions without having to play with real files. If this was an instance class, it would be easy.

1

It's much easier to refactor methods that are static. It discourages unnecessary references to field members that make the coupling tight. It's also easier to understand calling code because it explicitly passes any objects it interacts with.

0

Generally I avoid static methods when a single instance will work fine. That single instance can implement an interface and can be mocked easily. I'm not saying never but I rarely use statics. I tell my team if they want to use a static it should be cleared by the team. Almost never is my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.