this is a cyclic reference problem and it's usuall...
# announcements
j
this is a cyclic reference problem and it's usually solved by breaking apart responsibilities into three (or more) things which don't need to reference themselves instead of just two
🎯 1
n
Could you elaborate? How would you break apart the sample code I posted?
j
Your code offers no information as to why the instances need to reference each other so no, I can't really fix it without knowing a lot more
👏 1
the general rule here is to take the code from one of the classes which needs to know about the other and separate it into a third class
n
Here's a simplified example of some of the behavior:
Copy code
open class MainApplication() {
  val database = ... // provides database connection/DSL
  val dataLogger = DataLogger(this)
}

class DataLogger(val main: MainApplication) {
   init {
     onImportantEvent { main.database.insertData() }
   }
}
(obviously psuedo-code in some places, but hopefully that's more revealing)
n
then maybe the databse should be in its own component, and both main and other use it or database can be DI-ed
h
👆🏻
n
It's own component as in another class? An interface?
d
Your main entry point is too strictly coupled to your database as proven by the DataLogger. You want to reuse database from main and DataLogger so just extract it to say a Database (often called something like Repository) class and give main and DataLogger each an instance of it (could be the same instance), DI would be a way to solve it. DI is nothing magical, just a fancy way to give instances to dependent classes without actually instantiating the instances in those classes, often by passing them in the constructor.
👍🏻 1
n
in koin it could look like so
Copy code
val database: Database by inject()
j
then it lacks inversion of control. same exact problem as before.
if you're going to use a service locator you need to use it from the outside of the your dependencies and inject things into them
n
@jw are you referring to Davio's comments or Nikky's?