Tuesday, July 26, 2016

What is side effect of a function in programming?

Introduction

This articles explains what is side effect of function and advantages of avoiding side effects

Background

We all work with object oriented programming for years and our normal thinking goes to desinging application as similar to real world as much as possible. We use object oriented design principles to achieve the same. Shoud we really make everything object with its own class level properties? We are trying to investigate is there any better way to write code which is maintainable

What is side effect of a function

When we write a function / method in the first place, what is our intention? It does a job. It may or may not accept parameters. Sometimes it returns a value. That is the effect of the function invocation.
But there might be situations, that a function may start doing things which are not controlled by that  function. Look at the below code. 

//
// ES6 code which has a function with side effect.
//
class Calculator {
  constructor() {
    this.op = "add";
  }
  calculate(n1, n2) {
    if (this.op === "add") {
      this.op = "sub";
      return n1 + n2;
    } else {
      this.op = "add";
      return n1 - n2;
    }
  }
}


Here what is the effect? As consumers we call the calculate() the effect we are expecting is the calculated value. But what is happening here?

We get the calculated value. But in the mean time its doing something else on class level variable which we as consumers, don't expect.

It makes our next call gives different output for the same input values. Those are considered as side effect of the function. Side effect will be seen, if we look from the consumer's view.

Below is the code to invoke the function 3 times with same input.

var calc = new Calculator();
alert(calc.calculate(20, 12));
alert(calc.calculate(20, 12));
alert(calc.calculate(20, 12));

Drawbacks on functions with side effect

The functions with side effects make it difficult to reason about code. What is reasoning about code? If we simulate the working of code, it is little difficult as we need to remember the state too along with the steps. This makes it difficult to achieve development speed and often cause bugs as it is difficult to think about all the possibilities.

This again brings constraint on calling order especially when there are multiple threads using same object to call the methods. When those kind of scenarios occur, it would be difficult to reproduce the bug at the developer end. Normally when developers encounter these types of thread issues, they simply put a lock around critical section. That simply brings us the effect of old single core processors. Our program will not be able to take advantage of multi cores if we just put locks in our code as it make the threads wait for each other. This may lead to deadlocks as well.

What else brings side effect to a function

Not only changing the global state is considered side effect. Whatever we are doing to the state of outside world is considered side effects. Consider the modified code.

// ES6 code which has a function with side effect. It doen't alter class level variable.
class MyCalculator {
  calculate(n1, n2, op) {
    var result;
    if (op === "add") {
      result = n1 + n2;
    } else {
      result = n1 - n2;
    }
    console.log("success");
    return result;
  }
}

This seems like side effect free. But if we look at the logging code, we can see its changing the outer world. So has side effect. If somebody has run the below code before invoking above method, only alternate calls will succeed.

// Redirect the console.log
var shouldSuccess = true;
console.realLog=console.log;
console.log = function(msg) {
  if (shouldSuccess) {
    shouldSuccess = !shouldSuccess;
    console.realLog(msg);
  } else {
    shouldSuccess = !shouldSuccess;
    throw "I am tired!!"
  }
};

In the real scenarios, there might be situations similar to this and that will cause the function fail inconsistently.

Can we write everything without side effects

The world is stateful. Its not possible to write every method in production code to be side effect free. But we should try to minimize the side effect as much as possible. Especially when we are writing sequential algorithms, transformations etc...Also we can we immutable objects to avoid risks.

Points of Interest

There are concepts like pure functions, idem potent functions which are related to side effects. The function programming concept too trying to solve the side effects to an extent.

2 comments:

Blogger said...

Did you know that that you can make dollars by locking special sections of your blog or site?
Simply join AdscendMedia and embed their Content Locking tool.

Blogger said...

Quantum Binary Signals

Professional trading signals sent to your cell phone every day.

Follow our signals NOW & make up to 270% per day.