Home > Software design >  Android with Hilt: Do I have to inject helper classes?
Android with Hilt: Do I have to inject helper classes?

Time:09-19

My app includes many helper classes like the next ones:

  1. A class TMHttp with an "DownloadFile" or "IsOnline" methods (among others).
  2. A TMEmail class with a "SendEmail" method.
  3. A ImageHelper class with a "TakeScreenshot" or "CropBitmap" methods.
  4. TMImport/TMExport classes with "ImportData" and "ExportData" methods.
  5. A TMSession class with "LoginUser", "LogoutUser" and more such methods.
  6. A TMUtils class with methods like "GenerateRandom".
  7. A TMDialog class with methods like "CreateYesNoDialog" ... and many more.

And what I'd need to know -regarding DI- is if I have to inject them where needed -like I do with repository and services- or just create an instance of them. Do I have to inject every class in my app?

CodePudding user response:

I believe there is no strict answer to this question because it depends on the architecture of your project, the principles the team is using, the purpose and the complexity of the helper/util class, etc.

You need to decide it for each such helper/util class particularly, guided by the following advantages of Dependency injection:

  • Reusability of classes and decoupling of dependencies: It's easier to swap out implementations of a dependency. Code reuse is improved because of inversion of control, and classes no longer control how their dependencies are created, but instead work with any configuration.

  • Ease of refactoring: The dependencies become a verifiable part of the API surface, so they can be checked at the object-creation time or at compile time rather than being hidden as implementation details.

  • Ease of testing: A class doesn't manage its dependencies, so when you're testing it, you can pass in different implementations to test all of your different cases.

For example, I would argue like this:

A TMUtils class with methods like "GenerateRandom"

Likely, it's a quite simple helper method that basically can have a standard single implementation; it doesn't depend on other libraries, so I can freely use it without DI.

A class TMHttp with an "DownloadFile" or "IsOnline" methods (among others).

It's heavy and it depends on a lib and Android SDK then it makes sense to inject.

And so on.

  • Related