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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With