Chapter 2. A comprehensive example
Menu
- Comprehensive example
- Doing it wrong
- Doing it right
Telling you that a sauce béarnaise is “an emulsified sauce made from egg yolk and butter” doesn’t magically instill in you the ability to make one. The best way to learn is to practice; an example can often bridge the gap between theory and practice. Watching a professional cook making a sauce béarnaise is helpful before you try it out yourself.
When I introduced Dependency Injection in the last chapter, I presented a high-level tour to help you understand its purpose and general principles. However, this simple example didn’t do justice to DI. DI is a way to enable loose coupling, and loose coupling is first and foremost an efficient way to deal with complexity.
Most software is complex in the sense that it must address many concerns at the same time. Besides the business concerns (which may be complex in their own right), software must also address concerns related to security, diagnostics, operations, and extensibility. Instead of addressing all of these concerns in one big ball of mud, loose coupling encourages us to address each concern separately. It’s easier to address each concern in isolation—but ultimately we must still compose this complex set of concerns. Let’s take a look at a complex example to better showcase DI.