Functional Programming Flashcards
Key concepts of functional-style programming
- Functions as first-class objects
- Pure functions
- Higher-order functions
Functions as first-class objects
we can create an instance of a function as having a variable referencing that function instance. This is like referencing a String, List, or any other object. Moreover, functions can be passed as parameters to
other functions.
However, Java methods are not first-class objects. The best we can do is to rely on Java lambda expressions.
Pure functions
A pure function is a function whose execution has no side effects and the return value depends only on its input parameters.
If a method uses member variables or mutates the states of a member variable, then it is not a pure function.
Higher-order functions
takes one or more functions as parameters and/or returns another function as a result. Java emulates higher-order functions via lambda expressions.
In other words, in Java, a higher-order function is a method that gets one (or more) lambda expressions as arguments and/or returns another lambda expression.
Pure functional programming rules
- No state
- No side effects
- Immutable variables
- Favoring recursion over looping
No state?
By no state, we do not mean that functional programming eliminates state. Commonly, no state means that there is no external state to the function. In other words, a function may work with local variables that contain temporary states internally, but it cannot reference any member variables of the class/object it belongs to.
No side effects
By no side effects, we should understand that a function cannot change (mutate) any state outside of the function (outside of its functional scope). State outside of a function includes the following:
* The member variables in the class/object that contain that function
* The member variables that are passed as parameters to the function
* Or the state in external systems (for example, databases or files).
Immutable variables
Functional programming encourages and sustains the usage of immutable variables. Relying on immutable variables helps us to avoid side effects in a much easier and more intuitive way.
Favoring recursion over looping
Since recursion relies on repeated function calls to emulate looping, the code becomes more functional. This means that the following iterative approach for calculating factorials is not encouraged by functional programming.
Tail recursion?
Tail recursion is preferred when there are many recursive calls. In tail recursion, the function executes the recursive call as the last thing to do, so the compiler doesn’t need to save the function call as a frame in the recursion stack. Most compilers will optimize tail recursion, hence avoiding the performance penalty