Some people say that it is better to use dependency injection. Why is that?
I think it is better to have few global, easy accessible classes, rather than huge constructors.
Does it influence application speed in any way?
Mix of these two would be probably the best.
The main advantage will be decoupling, which will help with unit testing. This sort of depends entirely on how you code these "easily accessible classes".
The idea is this. A class decouples from implementation (class
) dependencies by only having a dependency on the contract (interface
). In your live environment you may never provide a new implementing class, but in your test environment you very likely will (be it a handmade stub, or a mocked class from a mocking framework).
Application speed would need profiling, but the use of a framework for DI would likely incur some overhead instead of you talking directly to a singleton that you know about. The important question: is this overhead a problem? Only performance expectations and profiling can tell you that. In my experience, the benefits far outweigh the negligible performance detriment.
You will probably be using static
classes and methods as your Globals. They do not have any performance implication. However, static classes do not lend themselves to testability.
What are the downsides to static methods?
Moreover, once your code becomes tightly coupled to static classes (Globals) you will not be able to replace them with alternate implementations in the future. So Globals may not be good design unless used in very simplistic situations.
Note that static classes and methods are compile time binding where as DI is run time binding. Helps you keep your classes loosely coupled.
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