Skip to content

Design Patterns

Dependency Injection

Handing in a dependency takes O(1) time (a constant amount) — it's just passing a reference in. The real cost is whatever that dependency does.

The idea, in plain English

Dependency injection means you get HANDED your tools instead of making them yourself. Picture a chef who gets today's ingredients from the kitchen, instead of growing their own vegetables. The chef can cook with whatever they're handed, so tomorrow's ingredients can be totally different, and the chef doesn't need to change at all. In code, an object receives the other objects it needs from the outside, instead of creating them itself.

How it works

  1. 1Instead of a class building the things it depends on inside itself, it accepts them as inputs — usually in its constructor (the setup method that runs when you create the object).
  2. 2Whoever creates the object decides which exact version to hand it: a real one, a fake one for testing, or a different brand entirely.
  3. 3The class just uses whatever it was handed, without caring which specific version it got.

When you'd use it

Use this when you want to swap parts easily — a real database vs. a fake one for tests, different payment providers, or different engines — without rewriting the class that uses them.

Common beginner mistakes

  • Don't let the class create its own dependency internally 'for convenience'. That locks you back into one fixed version.
  • Don't hand in so many small pieces that the constructor becomes a long, confusing list. Sometimes a few really do belong bundled together.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Gas car: Gas engine vroom -> car moving
Electric car: Electric engine hum -> car moving

Not sure this is the right topic? See the learning paths → or where this leads →