Side effects

In a computer program, when a function modifies any object/data outside its own scope, that is called a side effect. For instance, we often write functions that modify a global or static property, modify one of its arguments, raise an exception, write data to display or file, or even call another function which has a side effect.

For example, have a look at the following program:

class Calc { 
    var a:Int=0 
    var b:Int=0 
    fun addNumbers(a:Int = this.a,b:Int = this.b):Int {  
        this.a = a 
        this.b = b 
        return a+b 
    } 
} 
fun main(args: Array<String>) { 
    val calc = Calc() 
    println("Result is ${calc.addNumbers(10,15)}") 
} 

The preceding program is a simple object-oriented program. However, it contains side effects. The addNumbers() function modifies the state of the Calc class, which is bad practice in functional programming.

While we cannot avoid side effects in a few functions, especially where we are accessing IO and/or a database and so on, side effects should be avoided wherever possible.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.208.97