top of page

Pure Functions in Functional Programming


What is Pure Function?

Pure functions is one of the important concept in Functional programming. It is a function which

  1. Returns the same output for the same input value.

  2. Does not have any side effects. Side effects could be something which is included in this function like global variable.

Basically, pure functions does not depend on external entity.

Let’s see an example.

class Calculation {
    private int multiple(int a, int b) {
        return a * b;
    }
}
Calculation is a class which has a function called multiply. Here I am passing two parameters a and b. In any case, when I pass the same input, the output will be same. If I call this function multiple (4,3), I always get the result as 12. This is a pure function.

Let’s see an example of an impure function.

class Calculation {
    private int count = 0;
    private int multiple(int a, int b) {
        b += count++;
        return a * b;
    }
}
The above function is impure. There is a global variable which keeps incrementing as you call the multiple function, and the result of this function depends on the value of global variable count. This makes this an impure function.

Advantages of Pure functions

1. Readability

It is easy to read and understand as all the required inputs are provided to the function so no side effects are observed.

2. Testing

Writing unit test cases for pure functions is really simple and easy as there is no dependency on the external state. As there is no dependency on the global variables, we can easily write unit test cases for the pure functions.

 
 
 

Comments


people-2569234_1920.jpg

About Me

We are a Group of students who love to share there thoughts and journey..

 

Join My Mailing List

Thanks for submitting!

© 2020 Incorebmedia

bottom of page