Whenever you write a method, you fulfill a contract in a given scope. The narrower the scope is, the smaller the chance is that you write a bug.
When a method is static, you can’t access non-static members; hence, your scope is narrower. So, if you don’t need and will never need (even in subclasses) non-static members to fulfill your contract, why give access to these fields to your method? Declaring the method static
in this case will let the compiler check that you don’t use members that you do not intend to use.
And moreover, it will help people reading your code understand the nature of the contract.
That’s why it’s considered good to declare a method static
when it’s actually implementing a static contract.
In some cases, your method only means something relative to an instance of your class, and it happens that its implementation doesn’t actually use any non-static field or instance. In such cases, you would not mark the method static
.
Examples of where you would not use the static
keyword:
- An extension hook which does nothing (but could do something with instance data in a subclass)
- A very simple default behavior meant to be customisable in a subclass.
- Event handler implementation: implementation will vary with the class of the event handler but will not use any property of the event handler instance.