Thursday, July 02, 2020

Subtle Difference between NodeJS function and Arrow function.

There are 2 ways to define a function in NodeJS:

  • to define with the function keyword
  • to define with arrow "=>" keyword 

However, the functions defined by the two ways differ very subtly. Considering the .bind function on a function, which assigns an object as this of the function. the .bind function is available at functions created in both ways, but the function defined with arrow will not have access to this.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

This snippet demonstrated that after calling .bind, the arrow create function still doesn't have access to the correct this object. (verified in NodeJS v13.10.1)


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.