Skip to content
tezvyn:
Menu

Dependency Injection: Your Objects Shouldn't Create Their Own Helpers

Source: developer.android.comEasyHow cards are made

Dependency Injection: Your Objects Shouldn't Create Their Own Helpers

Instead of creating its own helpers (like a network client), an object receives them from an outside source. This is crucial for building testable Android apps, as it lets you swap a real UserRepository with a fake one during tests.

Why it exists

To decouple components. When an object creates its own dependencies, like val db = DatabaseHelper(context), it's tightly coupled to that specific implementation. This makes testing difficult because you can't easily replace the real database with a fake one. Swapping implementations becomes a major refactoring task. DI solves this by externalizing dependency creation.

The mental model

Think of a chef in a kitchen. A junior chef might run to the pantry to grab every ingredient they need (new Flour(), new Sugar()). A senior chef has a mise en place—all ingredients are prepped and provided to them before they start cooking. The chef doesn't create the ingredients; they are "injected" into their workspace. Your objects should be like the senior chef.

How it works

There are three main types of injection. First, Constructor Injection: dependencies are provided through the class's constructor. This is the most common and recommended approach. Second, Field Injection: dependencies are passed through public properties after the object is created, often used in Android frameworks like Activities where you don't control the constructor. Third, Method Injection: a dependency is passed into a specific method that needs it, not the whole object.

When to use it

Use DI for any non-trivial dependency your class needs to function. This includes network clients, database access objects (DAOs), shared preferences managers, and analytics trackers. It is the foundation of modern, scalable Android architecture.

When not to use it

Avoid DI for simple, self-contained value objects or data classes that have no external dependencies (like a User data class with just strings and integers). Overusing it for trivial, local objects can add unnecessary complexity.

One canonical example

A LoginViewModel needs a UserRepository to handle user data. Without DI, it would create its own: class LoginViewModel { private val repository = UserRepository() }. This is hard to test. With DI, it requests it in the constructor: class LoginViewModel(private val repository: UserRepository) { ... }. Now, in a unit test, you can easily pass a FakeUserRepository instead of the real one.

Interview question

According to the card, what is the most significant advantage of using Dependency Injection in an Android application?

  • a.It reduces the memory footprint of the application by deferring object creation.
  • b.It allows for easy swapping of component implementations, greatly improving testability.Correct
  • c.It automatically handles the lifecycle management of injected objects within Android components.
  • d.It ensures that all dependencies are initialized on a background thread, preventing UI freezes.
Why?

The card explicitly states that DI is "crucial for building testable Android apps" because it allows you to "swap a real UserRepository with a fake one during tests." While other options might describe benefits of good architecture or frameworks, they are not the primary advantage of DI as highlighted in the card. For example, DI itself doesn't inherently reduce memory footprint or manage lifecycles; it's about how dependencies are provided.

Just read this? Test yourself on what you have been reading.

Read the original → developer.android.com

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on android — each one lists the topics its interview covers.

See open roles