Pure vs impure functions definition and example

Described below are the important distinctions of Pure and Impure functions.

Pure function

  • Returned value depends on the values of the arguments
  • Pure functions do not call other systems or applications such as network or database calls
  • They do not use other variables besides their arguments
  • They are independent and only calculate a new value from its arguments
  • Pure functions will always return the same result given the same arguments
  • they also do not modify the arguments
  • Returns a new object
// Pure functions
function double(x) {
    return x + x;
}

function doubleAll(list) {
    // given an array it will not modify the array it will return a new object
    return list.map(double);
}

Impure function

  • Impure functions call some external system or application such as a database or network call
  • They reach out to other properties of the system or application
  • Modify the arguments passed to function
  • Returns same object or modified version of same object
// Impure functions
function double(x) {
    networkCall(x);
    return x + x;
}

function doubleAll(list) {
    for (let i = 0; i < list.length; i++) {
        list[i] = double(list[i]);
    }
    return list;
}

 

String to int without using Integer class in Java

An alternative to converting a String to int is using a custom implementation suing the Character.digit() method.

String number = "12345";
int radix = 10;
int result = 0;
for (int i = 0; i < number.length(); i++) {
    char c = number.charAt(i);
    int digit = Character.digit(c, radix);
    result *= radix;
    result += digit;
}
System.out.print(result);

Output

12345