Sobes.tech
Junior — Middle

What approaches can be used to avoid directly creating function instances in code?

sobes.tech AI

Answer from AI

To avoid directly creating an instance of a function (for example, an object or class) in the code, the following approaches are used:

  1. Factory Method — creates objects through special methods, hiding the details of creation.

  2. Dependency Injection — objects are passed into a class from outside, usually through a constructor or setter, which simplifies replacement and testing.

  3. Using interfaces and abstractions — code works with interfaces, and specific implementations are created and passed from outside.

  4. Lambda expressions and functional interfaces — instead of creating new classes, functions can be passed as parameters.

Example with dependency injection in Android (Kotlin):

interface ClickHandler {
    fun onClick()
}

class MyActivity(private val clickHandler: ClickHandler) {
    fun setup() {
        // Using the passed handler instead of creating a new one
        button.setOnClickListener { clickHandler.onClick() }
    }
}

This approach increases code flexibility and testability, and also makes maintenance and extension easier.

What approaches can be used to avoid directly… - sobes.tech