将方法声明为静态方法的好处是什么

我最近在 Eclipse 中查看了我的警告,发现了这个警告:

static warning

如果方法可以声明为 static,它将给出编译器警告。

[ edit ] Eclipse 帮助中的精确引用,重点是 private 和 final:

启用后,编译器将发出错误或警告 方法,它们是 二等兵期末考试,并且只引用静态 成员。

是的,我知道我可以关掉它,但我想 知道打开它的原因吗?

为什么把每个可能的方法都声明为静态方法是一件好事呢?

这会给性能带来好处吗? (在移动领域)

指出一个方法是静态的,我想这表明你没有使用任何实例变量,因此可以移动到一个 utils 样式类?

在一天结束的时候,我应该关闭这个“忽略”还是应该修复它给我的100多个警告?

你认为这只是额外的关键字,肮脏的代码,因为编译器将只是内联这些方法无论如何?(有点像你不声明每个变量,你可以最终 但你可以)。

26499 次浏览

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.

There is no concept with optimization here.

A static method is static because you explicitly declare that method doesn't rely on any instance the enclosing class just because it doesn't need to. So that Eclipse warning, as stated in documentation:

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

If you don't need any instance variable and your method is private (can't be called from outside) or final (can't be overriden) then there is no reason to let it be a normal method instead that a static one. A static method is inherently safer even just because you are allowed to do less things with it (it doesn't need any instance, you don't have any implicit this object).

The methods you can declare as static are the ones that don't require instantiation, such as

public class MyClass
{
public static string InvertText(string text)
{
return text.Invert();
}
}

Which you can then in return call out in any other class without instanciating that class.

public class MyClassTwo
{
public void DoSomething()
{
var text = "hello world";
Console.Write(MyClass.InvertText(text));
}
}

... But that's something you probably already know. It doesn't give you any real benefits per se, other than making it more clear that the method doesn't use any instance variables.

In other words, you can most safely just turn it off completely. If you know you will never use a method in other classes (in which case it should just be private), you don't need it to be static at all.

I've no info on the performance, I suppose it is marginally better at most, since the code does not need to do dynamic dispatch based on the type.

However, a much stronger argument against refactoring into static methods is that currently using static is considered bad practice. Static methods / variables do not integrate well into an object oriented language and also, hard to test properly. This is the reason why some newer languages forego the concept of static methods/variables altogether, or try to internalize it into the language in a way that plays better with OO (eg Objects in Scala).

Most of the time, you need static methods to implement functions that are only using parameters as an input and producing an output using that (eg utility/helper functions) In modern languages, there is a first class Function concept that allows that, so static is not needed. Java 8 will have lambda expressions integrated, so we are moving into this direction already.

See Samuel's answer on how the scope of the method changes. I guess, this is the main aspect of making a method static.

You also asked about performance:

There might be a tiny performance gain, because a call to a static method does not need the implicit "this" reference as parameter.

However, this performance impact is really tiny. Therefore, it's all about the scope.

Well, the Eclipse documentation says about the warning in question:

Method can be static

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

I think it pretty much says it all. If the method is private and final and only refers to static members, the method in question might just as well be declared static and by this, make evident that we only intend to access static content from it.

I honestly don't think there is any other mysterious reason behind it.

1. Declaring method static gives slight performance benefit, but what is more useful, it allows using it without having an object instance at hand (think of for example about factory method or getting a singleton). It also serves the documentational purpose of telling the nature of the method. This documentational purpose should not be ignored, as it gives immediate hint about the nature of the method to the readers of the code and users of the API and also serves as a tool of thinking for the original programmer - being explicit about the intended meaning helps you also think straight and produce better quality code (I think based on my personal experience, but people are different). For example, it is logical and hence desirable to distinguish between methods operating on a type and methods acting on an instance of the type (as pointed out by Jon Skeet in his comment to a C# question).

Yet another use case for static methods is to mimic procedural programming interface. Think of java.lang.System.println() class and the methods and attributes therein. The class java.lang.System is used like a grouping name space rather than an instantiable object.

2. How can Eclipse (or any other programmed or other kind of - biocomposable or non-biocomposable - entity) know for sure which method could be declared as static? Even if a base class is not accessing instance variables or calling non-static methods, by the mechanism of inheritance the things can change. Only if the method cannot be overridden by inheriting subclass, can we claim with 100% certainty that the method really can be declared static. Overriding a method is impossible exactly in the two cases of being

  1. private (no subclass can use it directly and does not even in principle know about it), or
  2. final (even if accessible by the subclass, there is no way to change the method to refer to instance data or functions).

Hence the logic of the Eclipse option.

3. The original poster also asks: "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?" This is a very good point. Sometimes this kind of design change is indicated by the warning.

It is very useful an option, which I would personally make sure to enable, were I to use Eclipse and were I to program in Java.

From the Android Performance guidelines:

Prefer Static Over Virtual If you don't need to access an object's fields, make your method static. Invocations will be about 15%-20% faster. It's also good practice, because you can tell from the method signature that calling the method can't alter the object's state.

http://developer.android.com/training/articles/perf-tips.html#PreferStatic

I was missing some numbers for the speed differences. So I tried to benchmark them which turned out to be not so easy: Java loop gets slower after some runs / JIT's fault?

I finally used Caliper and the results are the same as running my tests by hand:

There is no measurable difference for static/dynamic calls. At least not for Linux/AMD64/Java7.

The Caliper Results are here: https://microbenchmarks.appspot.com/runs/1426eac9-36ca-48f0-980f-0106af064e8f#r:scenario.benchmarkSpec.methodName,scenario.vmSpec.options.CMSLargeCoalSurplusPercent,scenario.vmSpec.options.CMSLargeSplitSurplusPercent,scenario.vmSpec.options.CMSSmallCoalSurplusPercent,scenario.vmSpec.options.CMSSmallSplitSurplusPercent,scenario.vmSpec.options.FLSLargestBlockCoalesceProximity,scenario.vmSpec.options.G1ConcMarkStepDurationMillis

and my own results are:

Static: 352 ms
Dynamic: 353 ms
Static: 348 ms
Dynamic: 349 ms
Static: 349 ms
Dynamic: 348 ms
Static: 349 ms
Dynamic: 344 ms

The Caliper Test class was:

public class TestPerfomanceOfStaticMethodsCaliper extends Benchmark {


public static void main( String [] args ){


CaliperMain.main( TestPerfomanceOfStaticMethodsCaliper.class, args );
}


public int timeAddDynamic( long reps ){
int r=0;
for( int i = 0; i < reps; i++ ) {
r |= addDynamic( 1, i );
}
return r;
}


public int timeAddStatic( long reps ){
int r=0;
for( int i = 0; i < reps; i++ ) {
r |= addStatic( 1, i );
}
return r;
}


public int addDynamic( int a, int b ){


return a+b;
}


private static int addStatic( int a, int b ){


return a+b;
}


}

And my own Test class was:

public class TestPerformanceOfStaticVsDynamicCalls {


private static final int RUNS = 1_000_000_000;


public static void main( String [] args ) throws Exception{


new TestPerformanceOfStaticVsDynamicCalls().run();
}


private void run(){


int r=0;
long start, end;


for( int loop = 0; loop<10; loop++ ){


// Benchmark


start = System.currentTimeMillis();
for( int i = 0; i < RUNS; i++ ) {
r += addStatic( 1, i );
}
end = System.currentTimeMillis();
System.out.println( "Static: " + ( end - start ) + " ms" );


start = System.currentTimeMillis();
for( int i = 0; i < RUNS; i++ ) {
r += addDynamic( 1, i );
}
end = System.currentTimeMillis();
System.out.println( "Dynamic: " + ( end - start ) + " ms" );


// Do something with r to keep compiler happy
System.out.println( r );


}


}


private int addDynamic( int a, int b ){


return a+b;
}


private static int addStatic( int a, int b ){


return a+b;
}


}