What are the preferences between using objects vs ...
# android
b
What are the preferences between using objects vs classes in kotlin. I know objects have some advantages depending on the use case, of singletons and late initialization. I have been leaning on objects but wanted to further understand the real advantages i’m getting as opposed to using a class
p
objects are singletons at the end, and is considered an antipattern for many reasons
b
Could you elaborate a bit more on how objects are antipatterns ?
The most important one is they are hard to replace for testing, they are not constructor injectable. The constructor is parameterLess
p
I would argue that that Stack Oveflow argument is weak. Objects can have injectable variables that allow complete testing. I have done over 100 projects using this approach achieving 100% code coverage in every single one of them. There were valid arguments against singletons in Java but in Kotlin you will be fine.
b
I’m not understanding why they are hard to replace for testing. They are easily fakeable with an interface
I also wouldn’t inject them in a constructor. I would use method injection as a param and just default it to the object, replacing it in a test using an interface
p
So it basically limits you to only parameter or method injection. For the case of an interface, do you mean something like this:
Copy code
interface ABC

object AnAbcObject() : ABC {

  var something: Int = 1

  fun someFun() { ... }

}

class B(abc: ABC) { ... }
// or 
class C { 
  
  var abc: ABC? = null
  
  setAbc(abc: ABC) { this.abc = abc }
}
In such a case that you have in your code class B or class C above. What is the benefit then of using an object. The easy part of using an object is that you can use bellow non testable code:
Copy code
AnAbcObject.something
AnAbcObject.someFun
If you are not doing above, why would you use an object in first place 🤷
👍 1
Also is true they are mockable using a static mocking library. But then it adds the constraint that you need to
set the mock
and
clean the mock
before other tests start. If forgetting to clean up other tests might use previous test leftovers.
And all that is just when it comes to testing, but the real danger behind Singletons is the fact that you are
sharing mutable memory
. If you are not careful about it, threading issues immediately start showing up. Regular Classes don’t have that problem since each instance share a different memory space.(Well, unless you access the same instance from multiple threads)
b
In such a case that you have in your code class B or class C above. What is the benefit then of using an object
Ya. i guess the only thing you’re getting is that an object would be lazily initialized.
👍 1
p
That's true right, it is initialized on first access