Refactoring 024 - Replacing Global Variables with Dependency Injection

Improve your code quality by eliminating hidden dependencies with dependency injection. Reducing coupling and improving testability will make your code cleaner and more maintainable. ??

martes, 11 de marzo de 2025 • 1 min read • Q2BSTUDIO Team

Company-Software-Apps

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:

  1. Identify global variables used in the code.
  2. Create an abstraction that encapsulates these variables.
  3. Pass dependencies explicitly via parameters or constructors.
  4. Refactor existing code to adopt the new structure with dependency injection.
  5. 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.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.