Table of Contents
Item 5: Erlang Best Practices - Prefer dependency injection to hardwiring resources
Introduction to Dependency Injection in [[Erlang]]
In Erlang, a concurrent, functional programming language designed for building scalable and fault-tolerant systems, dependency injection (DI) is a design pattern that promotes loose coupling between components by injecting dependencies (such as services, objects, or resources) into functions or modules, rather than hardwiring these dependencies directly within the code. This approach contrasts with hardwiring, where resources and dependencies are created or managed directly inside a module or function, leading to tightly coupled code that is harder to test, extend, and maintain. By preferring dependency injection over hardwiring resources, you can achieve more modular, testable, and maintainable code.
Advantages of Dependency Injection in [[Erlang]]
Preferring dependency injection over hardwiring resources offers several key advantages: 1. **Improved Testability**: DI allows you to easily replace real implementations with mocks or stubs during testing, making unit tests more isolated and reliable. 2. **Loose Coupling**: DI decouples modules and functions from their dependencies, allowing them to evolve independently. This results in a more flexible and maintainable codebase. 3. **Simplified Configuration Management**: DI patterns allow centralized management of dependencies, reducing complexity and making configuration changes easier. 4. **Better Separation of Concerns**: By separating the creation of dependencies from their usage, you adhere to the single responsibility principle, leading to more focused and maintainable code.
Example 1: Hardwiring vs. Dependency Injection in a Function
- Hardwiring Example
```erlang -module(user_service). -export([add_user/1]).
add_user(User) →
% Hardwiring the dependency DbConnection = {db_connection, "localhost", "mydb"}, save_user(DbConnection, User).
save_user({db_connection, Host, Db}, User) →
io:format("Saving user ~p to database ~p at ~p~n", [User, Db, Host]).```
In this example, the `user_service` module is responsible for creating its `DbConnection` dependency. This tight coupling makes the module harder to test, extend, and maintain.
- Dependency Injection Example
```erlang -module(user_service). -export([add_user/2]).
add_user(DbConnection, User) →
save_user(DbConnection, User).
save_user({db_connection, Host, Db}, User) →
io:format("Saving user ~p to database ~p at ~p~n", [User, Db, Host]).```
Here, the `user_service` module receives its `DbConnection` dependency as a parameter. This loose coupling allows for greater flexibility and makes the module easier to test and modify.
Example 2: Using Higher-Order Functions for Dependency Injection
In Erlang, higher-order functions can be used to inject dependencies, allowing you to create more flexible and reusable code.
- Dependency Injection with Higher-Order Functions
```erlang -module(user_service). -export([create_add_user/1]).
create_add_user(DbConnection) →
fun(User) -> save_user(DbConnection, User) end.
save_user({db_connection, Host, Db}, User) →
io:format("Saving user ~p to database ~p at ~p~n", [User, Db, Host]).
% Usage example: 1> AddUser = user_service:create_add_user({db_connection, “localhost”, “mydb”}). 2> AddUser(“John Doe”). ```
In this example, the `create_add_user` function returns a new function that has the `DbConnection` dependency injected. This approach allows you to create reusable functions with different dependencies.
Example 3: Using Application Configuration for Dependency Injection
Erlang's application configuration management allows you to inject dependencies based on the environment or configuration settings, centralizing dependency management.
- Dependency Injection with Application Configuration
```erlang -module(user_service). -export([add_user/1]).
add_user(User) →
DbConnection = application:get_env(my_app, db_connection), save_user(DbConnection, User).
save_user({db_connection, Host, Db}, User) →
io:format("Saving user ~p to database ~p at ~p~n", [User, Db, Host]).
% Configuration example: {my_app, [
{db_connection, {db_connection, "localhost", "mydb"}}]}. ```
In this example, the `user_service` module retrieves the `DbConnection` dependency from the application's configuration. This approach centralizes dependency management and makes it easier to modify or swap dependencies based on the environment.
Example 4: Testing with Dependency Injection
One of the main benefits of dependency injection is the ability to test modules and functions more effectively by injecting mock or stub dependencies.
- Testing a Function with Mock Dependencies
```erlang -module(user_service_test). -export([test_add_user/0]).
test_add_user() →
MockDbConnection = {db_connection, "mockhost", "mockdb"}, User = "Test User", user_service:add_user(MockDbConnection, User), io:format("Test passed: User ~p was added using mock DB.~n", [User]).
% Run the test: 1> user_service_test:test_add_user(). ```
In this example, a mock `DbConnection` is injected into the `add_user` function for testing purposes. This allows you to test the function without relying on a real database connection, making your tests faster and more reliable.
When to Prefer Dependency Injection in [[Erlang]]
Dependency injection is particularly useful in the following scenarios: - **Complex Applications**: In large or complex applications, DI helps manage the interdependencies between modules and functions more effectively. - **Test-Driven Development (TDD)**: If you follow TDD practices, DI makes it easier to create testable functions and modules by allowing dependencies to be injected as mocks or stubs. - **Configuration-Driven Applications**: When building applications that rely on different configurations, DI helps manage and inject these configurations throughout the application. - **Reusable Libraries**: DI is beneficial in systems designed with reusable libraries, where dependencies need to be loosely coupled and easily interchangeable.
Conclusion
In Erlang, preferring dependency injection over hardwiring resources is a best practice that leads to more maintainable, testable, and flexible code. By injecting dependencies, you decouple your modules and functions from their dependencies, making it easier to manage and extend your application. This approach aligns well with modern Erlang development practices, especially when using higher-order functions or application configuration to manage dependencies.