Friday, February 21, 2020

Java 8: Passing a Method as an Argument with & without Side Effects

Pure function in Computer Science is defined as a method without side effect. Given the same input to a pure function, the developer can expect the same output. This makes the code simpler. This is typically implemented as static function in Java 8.

In contrast, when a method may have side effects, which could be due to internal states stored in an object or I/O actions, the outcome of the method is hard to predict. Thus harder to test.

To pass a function as an argument to a method in Java 8, you may perform on a static method or an instance method: https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html
In this example, we have a static method passed without side effect, while passing an instance method can potentially introduce side effects unaware to the programmer.
The output from the above code shows that states may be allowed to exist in an argument passed with an instance method:
/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/bin/java ...
3
14
15

Process finished with exit code 0
An instance method can be a pure function, too. However, passing an instance method as an argument opens up for later developers to introduce side effects in the function.

Stay with static method when trying to make a pure function, and use instance method only when you intend to introduce states to a function.