In my previous post, we discussed about why we should consider to use functional programming. Now, let's delve into what functional programming in Java is.
What is pure functional programming?
Shortly, functional programming is programming using functions. A function corresponds to a mathematical function such as log, sin. Basically, it takes zero or more arguments, give one or more result, and has no side effects.We can't completely program in pure functional style in Java
Why? For example, calling Scanner.nextLine twice typically gives different result.So, it's just called "functional-style programming". How is that?
- There is no mutating structures visible to callers. That means your side effect may not be visible to a program, but it's visible to the programmer in terms of slower execution.
- A function or method shouldn't throw any exceptions (follows the concept "pass arguments, return result"). We can use types like Optional<T> instead.
- For pragmatic reasons, we can accept some code that can't be strictly described as functional, e.g: some form of log file.
We call it "no visible side effects" or referential transparency
With functional-style programming, we follow the rule "no visible side-effects" includes no mutating structures visible to callers, no I/O and no exceptions. This concept is called "referential transparency". A function is referentially transparent if it always returns the same result value when called with the same argument value. For example, "huong".replace("h", "H") but Random.nextIntWill function-style programming replace object-oriented programming?
Why? And, why not? These are just programming styles. It depends!In practice, Java programmers have always mixed object-oriented and functional-style programming styles.
- Object-oriented programming style: everything is an object and programs operate by updating fields and calling methods that update their associated object.
- Functional-style programming style: referential transparency. It helps enable you to write programs that are more modular and more suitable for multicore processors. These ideas are as additional weapons in your programming armory.
Reference
[1]. Alan Mycroft and Mario Fusco, Java 8 in Action: Lambdas, Streams, and Functional-style Programming. Part 4. Beyond Java 8.