The Solution: Dependency Inversion

What we want is to be able to configure PassphraseRepository at runtime in two different ways:

The recommended approach for this sort of pattern is to use dependency inversion. Basically, rather than PassphraseRepository creating a SecureRandom or having one passed in on every call, PassphraseRepository gets created with the desired SecureRandom instance. We push dependencies (SecureRandom) into the things that use those dependencies (PassphraseRepository) as part of setting up the singletons.

Dependency inversion is usually implemented using “dependency injectors”, “service locators”, or hybrid solutions. The details of the differences between those specific approaches is beyond the scope of this book — see this Stack Overflow discussion as an example of the long debates that are had regarding them.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.