By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
World of SoftwareWorld of SoftwareWorld of Software
  • News
  • Software
  • Mobile
  • Computing
  • Gaming
  • Videos
  • More
    • Gadget
    • Web Stories
    • Trending
    • Press Release
Search
  • Privacy
  • Terms
  • Advertise
  • Contact
Copyright Β© All Rights Reserved. World of Software.
Reading: Refactoring 024 – Replace Global Variables with Dependency Injection | HackerNoon
Share
Sign In
Notification Show More
Font ResizerAa
World of SoftwareWorld of Software
Font ResizerAa
  • Software
  • Mobile
  • Computing
  • Gadget
  • Gaming
  • Videos
Search
  • News
  • Software
  • Mobile
  • Computing
  • Gaming
  • Videos
  • More
    • Gadget
    • Web Stories
    • Trending
    • Press Release
Have an existing account? Sign In
Follow US
  • Privacy
  • Terms
  • Advertise
  • Contact
Copyright Β© All Rights Reserved. World of Software.
World of Software > Computing > Refactoring 024 – Replace Global Variables with Dependency Injection | HackerNoon
Computing

Refactoring 024 – Replace Global Variables with Dependency Injection | HackerNoon

News Room
Last updated: 2025/03/10 at 2:22 PM
News Room Published 10 March 2025
Share
SHARE

Break Hidden Dependencies for Cleaner Code

TL;DR: Replace global variables with dependency injection to improve testability and reduce coupling. πŸ’‰

Problems Addressed πŸ˜”

https://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-vii-8dk31x0

https://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-xiv

https://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-xxii

Steps πŸ› οΈ

  1. Identify global variables used across your codebase.
  2. Create a real-world abstraction to encapsulate these variables.
  3. Pass dependencies explicitly via function parameters or constructors.
  4. Refactor existing code to use the new dependency-injected structure.
  5. Remove the original global variable declarations.

Sample Code πŸ’»

Before ❌

// This global variable holds the API configuration  
const globalConfig = { apiUrl: "https://api.severance.com" };  

function fetchOuties() {  
  return fetch(`${globalConfig.apiUrl}/outies`);  
  // globalConfig is NOT passed as parameter
}

After πŸ‘‰

function fetchOuties(parameterConfig) {  
  return fetch(`${parameterConfig.apiUrl}/outies`);  
  // 1. Identify global variables
  // used across your codebase.
  // 4. Refactor the existing code 
  // to use the new dependency-injected structure. 
}  

const applicationConfig = { apiUrl: "https://api.severance.com" };  
// 2. Create a real-world abstraction
// to encapsulate these variables.

fetchOuties(applicationConfig); 
// 3. Pass dependencies explicitly 
// via function parameters or constructors.

//  const globalConfig = { apiUrl: "https://api.severance.com" };  
// 5. Remove the original 
// global variable declarations.

// Why Is 'config' a Dependency?
// Because:
// outies() depends on knowing the API URL to work
// Without this information, 
// The function can't perform its core task
// The dependency is 
// explicitly declared in the function signature

A Step Beyond: API Reification

class ApiService {
  constructor(parameterConfig) {
    this.variableConfig = parameterConfig;
  }
  
  // parameterConfig, variableConfig
  // and applicationConfig
  // are very bad names. 
  // They are here to emphasize the change

  fetchOuties() {
    return fetch(`${this.variableConfig.apiUrl}/outies`);
  }
}

const apiService = 
  new ApiService({ apiUrl: "https://api.severance.com" });
apiService.fetchOuties();

Type πŸ“

Safety πŸ›‘οΈ

This refactoring is safe if you audit all global variable references and thoroughly test the code after injection.

Why is the Code Better? 🌱

Testability: Dependencies can be replaced (not mocked) for unit tests.

Explicit Contracts: Functions declare what they need.

Scalability: Configuration changes don’t require code edits.

Coupling: Code is less coupled.

How Does it Improve the Bijection? πŸ—ΊοΈ

By making dependencies explicit, the code mirrors real-world interactions where components rely on declared inputs, not hidden state.

You also reduce Coupling which is usually the more important problem you must solve.

Limitations ⚠️

Over-injection can lead to parameter bloat.

Common Misconceptions

“But it’s just a parameter!”

  • Exactly! Passing dependencies via parameters is Dependency Injection. Frameworks often obscure this basic principle.

“This is too simple to be DI!”

  • Dependency Injection doesn’t require complex frameworks. This is a pure, framework-less injection.

“Dependency Injection vs Dependency Inversion”

  • Inversion is the principle (why). It tells you to depend on abstractions to reduce coupling.
  • Injection is the practice (how). It’s one way (there are many others) to apply the principle by passing dependencies from outside instead of creating them inside a class.

Refactor with AI πŸ€–

You can use AI tools to analyze your codebase and identify global variables.

The AI can suggest where to implement dependency injection and help generate the necessary interfaces or classes for your dependencies.

Try Them! πŸ› 

Remember: AI Assistants make lots of mistakes

Suggested Prompt: 1. Identify global variables used across your codebase.2. Create a real-world abstraction to encapsulate these variables. 3. Pass dependencies explicitly via function parameters or constructors. 4. Refactor existing code to use the new dependency-injected structure. 5. Remove the original global variable declarations.

Level πŸ”‹

See also πŸ”

Credits πŸ™

Image by Petra on Pixabay


This article is part of the Refactoring Series.

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Twitter Email Print
Share
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article PS5 Pro games set for huge boost from AMD’s FSR 4 upscaling
Next Article The Tesla protests are getting bigger β€” and rowdier
Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Stay Connected

248.1k Like
69.1k Follow
134k Pin
54.3k Follow

Latest News

The Tech Guys Are Fighting. Literally.
News
2025’s most romantic horror movie just crashed the Netflix top 10 β€” and it’s a frontrunner for my favorite film of the year
News
Galaxy S25 Edge leak reveals all the cases you’ll need to keep the super-thin phone safe
News
β€˜Teacher of the Year’ jailed for sexually abusing elementary pupils
News

You Might also Like

Computing

vs. Calendly: Which Planner App is Better? |

27 Min Read
Computing

GSoC 2025 Projects: AI-Powered Log Analyzer For Fedora, Better AMD ROCm On Debian

4 Min Read
Computing

The Linux Kernel Dropping Its Unused Built-In Software Echo Cancellation Code

2 Min Read
Computing

Intel oneDNN 3.8 Brings More CPU & GPU Performance Optimizations

3 Min Read
//

World of Software is your one-stop website for the latest tech news and updates, follow us now to get the news that matters to you.

Quick Link

  • Privacy Policy
  • Terms of use
  • Advertise
  • Contact

Topics

  • Computing
  • Software
  • Press Release
  • Trending

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

World of SoftwareWorld of Software
Follow US
Copyright Β© All Rights Reserved. World of Software.
Welcome Back!

Sign in to your account

Lost your password?