Sobes.tech
Junior — Middle

Can you explain what is meant by a side effect in programming?

sobes.tech AI

Answer from AI

A side effect in programming is any change in the program's state or interaction with the external world that occurs during the execution of a function or method, beyond returning a value. For example, writing to a database, changing a global variable, outputting to the screen, or sending a network request — all of these are side effects.

Side effects are important because they affect the predictability and testability of the code. Functions without side effects (pure functions) always return the same result for the same inputs and do not alter the program's state.

Example of a side effect in Kotlin for Android:

var counter = 0

fun incrementCounter() {
    counter++ // changing external state — side effect
}

fun getCounter(): Int {
    return counter // function without side effect
}