Blundell Blundell - 1 year ago 44
Java Question

What is the gain from declaring a method as static

I've recently been looking through my warnings in Eclipse and come across this one:

static warning

It will give a compiler warning if the method can be declared as static.

[edit] Exact quote within the Eclipse help, with stress on private and final:

When enabled, the compiler will issue an error or a warning for
methods which are private or final and which refer only to static

Yes I know I can turn it off, but I want to know the reason for turning it on?

Why would it be a good thing to declare every method possible as static?

Will this give any performance benefits? (in a mobile domain)

Pointing out a method as static, I suppose is showing that you don't use any instance variables therefore could be moved to a utils style class?

At the end of the day should I just turn this off 'ignore' or should I fix the 100+ warnings it has given me?

Do you think this is just extra keywords that dirty the code, as the compiler will just inlines these methods anyway? (kind of like you don't declare every variable you can final but you could).

Answer Source

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.