Search code examples
androidclassobjectsingletondagger-hilt

What should I use between object class and Hilt @Singleton class. in Android


 object A { ... }
 @Singleton class B { ... }

I am new to Hilt and assuming that those 2 classes are technically the same, but B is harder to implement, due to DI complexity, only limited to use in EntryPoints. I would like to know the advantages of using @Singleton instead of object class. Is it faster in terms of performance?


Solution

  • I wouldn't say that it's really harder to implement, especially if your whole app uses Hilt. Like yeah, it's 3-5 more lines of code. But in general, if you need a singleton, it means that it holds some data/passes it somewhere further/does some extra work by itself. With objects it's impossible to have constructor fields, and it's a very crucial part of any class that does something more than usual static functions-helpers.

    Let's say you have a class A that writes or reads to your database. You have to

    • either inject your DAO in the constructor,
    • create it manually in the class A as a class field - and that already violates the principle of having loosely-coupled classes and makes testing absurdly complicated,
    • pass your DAO with each function as a function parameter - but it's an obviously awful design, I won't stop here.

    Also by having your dependencies injected instead of created inside of the class, you can achieve some flexible substitutes of implementations (one interface - 5 implementations - different injections based on your needs/flavors/build setups, abstract and clean). It's easier to test these classes - you can mock your constructor parameters instead of making class fields non-private and mocking them after that.

    And if you want a usual object like TimeHelper or something like that, the same could be achieved by using top-level functions.