+ 5

[ CHALLENGE ]: dependency injection

Show an implementation of dependency injection in your favourite language AND describe in what situation you would use dependency injection.

6th Feb 2018, 9:03 PM
Freddy
1 Answer
+ 2
Here is an example of dependency injection in different languages. If you run it, you will get this text: ********************************* Demo that shows usage of dependency injection Dependency injection is used for hardware abstraction, which has the following advantages: - I can simply use a simulator if I don't have hardware - if the hardware ever changes, I only need to implement a new implementation of the interface to support the new hardware, the rest of the system stays the same! - I can use mocks to unit test my class without having an implementation at all! Demo: calling DoIt that switches the light on and off: LightSimulator: switched light ON LightSimulator: switched light OFF ********************************* Any code that depends on other code can benefit from dependency injection: you get a clear separation between what you need and *how* it's implemented. This makes your code easier to (unit) test and more resilient to changes. C#: https://code.sololearn.com/cY9XoZEnG3M5/#cs Java: https://code.sololearn.com/cwtUzejrEncH/#java C++: https://code.sololearn.com/ckfFj1tn00SG/#cpp C: https://code.sololearn.com/cgFqvBW20pPj/#c Python: https://code.sololearn.com/c0F2op5hX8E0/#py
9th Feb 2018, 9:26 AM
Freddy