Sobes.tech
Junior — Middle

What methods can be used to implement branching logic in programming code?

sobes.tech AI

Answer from AI

To implement branching logic in Android (Java/Kotlin) code, several methods can be used:

  1. Conditional operators (if-else, when in Kotlin): the simplest way to choose a branch of execution.

  2. switch operator (Java) or when (Kotlin): convenient when there are many options.

  3. Polymorphism: creating class hierarchies with overridden methods, allowing logic selection through objects.

  4. Strategy (design pattern): encapsulating different algorithms into separate classes and selecting the appropriate one at runtime.

  5. Functional approaches: using lambdas and higher-order functions to pass logic.

Example with when in Kotlin:

fun process(input: Int) {
    when (input) {
        1 -> println("Branch 1")
        2 -> println("Branch 2")
        else -> println("Other branch")
    }
}

This approach makes it easy to extend and maintain branching logic.