Friday, January 6, 2017

Pure Functions

This post discusses one of the important aspects of functional programming, Pure Function using Java example.

Pure functions are side-effect free functions or stateless functions. The output of pure functions depends purely (or completely) on input. What side-effect free basically means is that pure functions should not modify argument as well as any other state variables. 

Now, the obvious question is why is it so important. We will see later how it's one of the important ingredients for functional and Reactive programming. Let take a simple Java class to understand pure functions.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package functional;

import java.util.Random;

public class PureFunction {
 private int state = 420;

 // pure function
 public int addTwo(int x) {
  return x + 2;
 }

 // Impure function
 public int addState(int x) {
  return x + state;
 }

 // Impure Function
 public int randomizeArgument(int x) {
  Random r = new Random(1000);
  return x + r.nextInt(1000);
 }
}

Method, addTwo purely depends on its input/argument. No matter how many times you call it, it will behave in a predictable manner (i.e just add 2 to the argument and return the added number as the response). While the response of the other two methods (addState and randomizeArgument) is not going to be consistent even if it's called with same argument multiple times. The response of method addState depends on the instance variable of the class. If it gets mutated somewhere else, the response of the method will not be consistent. Similarly, the randomizedArgument method response will vary depending on the random value.

Let's cover some of the important points

  • If a pure function references any instance variable of the class, then that instance variable should be declared as final.
  • Pure functions help in highly concurrent and scalable environment by making the behavior predictable. 
  • You get parallelism free of cost if your method doesn't access a shared mutable data to perform its job. 

--happy learning !!!


No comments:

Post a Comment