Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static provide method in Dagger2

Why should use static modifier before the provide method?

Even though I remove the static modifier, dagger2 works correctly.

@Provides static Pump providePump(Thermosiphon pump) {
    return pump;
}
like image 675
Sandy Lin Avatar asked Jul 27 '16 08:07

Sandy Lin


1 Answers

Both styles work; whether you keep the method static is entirely up to you and your normal "should this be a static method" judgment in plain old Java. Here, pump doesn't have any use for a module instance, so the method can easily be static.

Static method calls are faster, particularly in Android, because they avoid a virtual method table lookup. This may also make them easier for compilers, JIT runtimes, or static analysis tools to inline. I'd surmise you'd open up similar advantages by making the class or method final.

There may also be a slight improvement in readability given that a static method can't be subject to instance fields, but that's up to you.

If you are confident that your @Provides method's behavior is not subject to change including in tests, then you can take advantage of the performance/readability increase. However, if you need to refer to module state or want to allow subclass/testing overrides, then an instance method is necessarily the right call.

like image 197
Jeff Bowman Avatar answered Nov 24 '22 14:11

Jeff Bowman