Taming Nondeterminism with Dependency Injection

Take back control of your code!

Haki Benita

Development Programming Software Design Testing

See in schedule

There are many sources of nondeterminism in code such randomness, IO, environment variables, databases and many more. Nondeterminism is a source of confusion, and it makes testing difficult. One way to control nondeterminism is using the dependency injection pattern.

In this talk I'll guide the audience through a series of problems that demonstrate how nondeterminism can pose incredible challenges even in simple code. Tackling one problem after another, I gradually integrate dependency injection into the code to address these challenges!

A rough outline of the talk:

- Present a problem that involves nondeterminism (test a function that returns tomorrow's date)
- Attempt to test in conventional ways (`datetime` cannot be mocked without external packages...)
- Offer solution (Inject literal values... show how simple it is to test)
- Present a function that requires more than a literal (a function the requires the current time more than once)
- Demonstrate injection of functions and services (Using nominal typing, e.g using ABC)
- Present the dependency injection pattern
- Replace AC with structural subtyping (Using`typing_extensions.Protocol`)
- Conclusion

After watching this talk, I expect my audience to learn and understand the following:

- The challenges nondeterminism poses
- How to identify nondeterminism in code
- What dependency injection is, and how it addresses challenge related to nondeterminism
- How to implement and integrate dependency injection into Python code

Type: Talk (30 mins); Python level: Intermediate; Domain level: Intermediate

Haki Benita

Haki Benita

Haki is a software developer and a technical lead. He takes special interest in databases, web development, software design and performance tuning. Haki also writes about development and performance in his blog hakibenita.com.