In the code above I'm implicitly depending on standard input. So standard input is a dependency of the function. Among other things it makes that code harder to test.
The code is okay but one way in which it can be improved is by making the dependency on standard input explicit. Here's how:
Pass the dependency as an argument which makes it explicit. The function now takes a file like object which I defaulted to standard input since that would be the typical use case.
What have we gained? The code is much easier to test and understand because you know what depends on what. It's dependencies are explicit.
Passing your dependencies via arguments to functions is one way to "inject your dependencies", hence the term "dependency injection".
If you want to see how it helps with testing in a real project then you can read these examples from my Python Whitespace interpreter project:
peripherals: Notice how Keyboard uses standard input and TestKeyboard uses StringIO.
In the code above I'm implicitly depending on standard input. So standard input is a dependency of the function. Among other things it makes that code harder to test.
The code is okay but one way in which it can be improved is by making the dependency on standard input explicit. Here's how:
Pass the dependency as an argument which makes it explicit. The function now takes a file like object which I defaulted to standard input since that would be the typical use case.
What have we gained? The code is much easier to test and understand because you know what depends on what. It's dependencies are explicit.
Passing your dependencies via arguments to functions is one way to "inject your dependencies", hence the term "dependency injection".
If you want to see how it helps with testing in a real project then you can read these examples from my Python Whitespace interpreter project:
Keyboard
uses standard input andTestKeyboard
usesStringIO
.