Break Hidden Dependencies for Cleaner Code
Summary: Replacing global variables with dependency injection improves testability and reduces coupling.
Problems it solves:
- Hidden dependencies
- High coupling
- Testing difficulties
- Maintainability issues
- Misuse of the Singleton pattern
Steps to improve the code:
- Identify global variables used in the code.
- Create an abstraction that encapsulates these variables.
- Pass dependencies explicitly via parameters or constructors.
- Refactor existing code to adopt the new structure with dependency injection.
- Remove the original global variable declarations.
Example before refactoring:
// Global variable storing the API configuration
const globalConfig = { apiUrl: https://api.severance.com };
function fetchOuties() {
return fetch(`${globalConfig.apiUrl}/outies`);
// globalConfig is not passed as a parameter
}
Example after refactoring:
function fetchOuties(parameterConfig) {
return fetch(`${parameterConfig.apiUrl}/outies`);
}
const applicationConfig = { apiUrl: https://api.severance.com };
fetchOuties(applicationConfig);
Further improvement: Creating a service class
class ApiService {
constructor(parameterConfig) {
this.variableConfig = parameterConfig;
}
fetchOuties() {
return fetch(`${this.variableConfig.apiUrl}/outies`);
}
}
const apiService =
new ApiService({ apiUrl: https://api.severance.com });
apiService.fetchOuties();
Advantages of this approach:
- Testability: Dependencies can be replaced in unit tests.
- Explicit contracts: Functions declare what data they need.
- Scalability: Facilitates changes in configuration.
- Less coupling: Reduces dependency between modules.
Limitations: If overused, injection can lead to an excess of parameters and make the code harder to read.
About Q2BSTUDIO:
At Q2BSTUDIO, experts in development and technology services, we implement principles like dependency injection to ensure scalable, maintainable, and high-quality software. We apply best practices so our clients obtain efficient and easily evolvable technological solutions.





