Refactorización 024 - Reemplazo de Variables Globales con Inyección de Dependencias

Mejora la calidad de tu código eliminando dependencias ocultas con inyección de dependencias. Reducir el acoplamiento y mejorar la testabilidad hará tu código más limpio y mantenible. ??

11 mar 2025 • 1 min read • Q2BSTUDIO Team

Empresa-Software-Apps

Rompe las Dependencias Ocultas para un Código Más Limpio

Resumen: Reemplazar las variables globales con inyección de dependencias mejora la capacidad de prueba y reduce el acoplamiento.

Problemas que resuelve:

  • Dependencias ocultas
  • Alto acoplamiento
  • Dificultades en pruebas
  • Problemas de mantenibilidad
  • Uso indebido del patrón Singleton

Pasos para mejorar el código:

  1. Identificar variables globales usadas en el código.
  2. Crear una abstracción que encapsule estas variables.
  3. Pasar las dependencias explícitamente mediante parámetros o constructores.
  4. Refactorizar el código existente para adoptar la nueva estructura con inyección de dependencias.
  5. Eliminar las declaraciones originales de variables globales.

Ejemplo antes de refactorización:

// Variable global que almacena la configuración de la API  
const globalConfig = { apiUrl: https://api.severance.com };  

function fetchOuties() {  
  return fetch(`${globalConfig.apiUrl}/outies`);  
  // globalConfig no se pasa como parámetro
}

Ejemplo después de refactorización:

function fetchOuties(parameterConfig) {  
  return fetch(`${parameterConfig.apiUrl}/outies`);  
}  

const applicationConfig = { apiUrl: https://api.severance.com };  

fetchOuties(applicationConfig); 

Mejorando aún más: Creando una clase de servicio

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();

Ventajas de este enfoque:

  • Testabilidad: Se pueden reemplazar dependencias en pruebas unitarias.
  • Contratos explícitos: Las funciones declaran qué datos necesitan.
  • Escalabilidad: Facilita cambios en la configuración.
  • Menos acoplamiento: Reduce la dependencia entre módulos.

Limitaciones: Si se usa en exceso, la inyección puede generar un exceso de parámetros y dificultar la lectura del código.

Sobre Q2BSTUDIO:

En Q2BSTUDIO, expertos en desarrollo y servicios tecnológicos, implementamos principios como la inyección de dependencias para garantizar software escalable, mantenible y de alta calidad. Aplicamos las mejores prácticas para que nuestros clientes obtengan soluciones tecnológicas eficientes y fáciles de evolucionar.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

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.