Pure function:
Below are not a pure function:
A pure function is a function, where
1. The return value only depends on its arg and always return the same value for the same argument.
2. They do not have any side effects.
3. They do not modify arguments, which are passed to them.
Example of a pure function:
Example 1:
public static int count=0;
public static int getCount() {
return count++;
}
Here getCount() returns different value on each invocation.
Hence it's not a pure function.
Example 2:
private static int count=0;
public static int getCount() {
return count;
}
Even though the getCount method return 0 in every invocation it is not dependent on its argument(s), which is inface in this case is void. Hence its not a pure function.
Example 3:
public List addItem(List list,Integer i) {
list.add(i);
return list;
}
Modifies the argument. Hence it has a side effect.
To make it pure function you can write code like this
Comments
Post a Comment