Skip to content

Commit

Permalink
Docs/ioc (#23)
Browse files Browse the repository at this point in the history
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Hynek Schlawack <[email protected]>
  • Loading branch information
3 people authored Aug 9, 2023
1 parent cb7647c commit 0c009c1
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions docs/glossary.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,13 +180,27 @@ IoC
See {term}`Inversion of Control`.

Inversion of Control
Inversion of Control is too complicated and essential to explain in a few sentences.
So if you feel like you haven't fully grokked it, we *strongly* recommend consulting the links at the end of this entry.
Inversion of Control is a complicated name for a simple idea.

It's about accepting that separating a big ball of mud into small modules is still a lot of dirt, just spread out – which is worse.
Instead, it's necessary to break the coupling between classes and modules – and achieve loose coupling.
In the following code, we have a function that adds a user to a database then sends them an email. To do that, it needs an `SmtpSender` and a `DbConnection`
which it constructs. This makes the code hard to test, since we don't want our unit tests to send people emails.

The most widespread method to achieve that is {term}`Dependency Injection`.
```python
def add_user_to_org(email: str):
smtp = SmtpSender()
db = get_database_connection()

try:
user = db.create_user(email)
smtp.send_welcome_email(user)
except DuplicateUserError:
log.warning("Duplicate user", email=email)
```

To fix that, we need to take _control_ of the dependencies out of the function, and provide them somehow, usually through dependency injection.

Why do we say IoC and not just dependency injection? Inversion of Control is a broader term that applies to any situation where we "invert" the
flow of control, so that lower-level code (frameworks, data access layers etc.) invoke our higher-level code (the business logic we care about).

::: {seealso}

Expand Down

0 comments on commit 0c009c1

Please sign in to comment.