Home >Java >javaTutorial >Example explanation of functional programming in Java8
Functional programming, this word consists of two nouns, function and programming. I don’t need to explain the word programming, everyone does it. Function, in fact, it is not unfamiliar to separate this word. So what is the combination of the two? The following article mainly introduces you to the relevant information about Java8 functional programming. Friends who need it can refer to it. .
Preface
In a previous article we quickly learned lambda and Stream, in this chapter we review and understand functional expressions Programming ideas. We keep mentioning the term functional, does it refer to lambda? If so, what benefits can you get from adopting functional programming?
Thinking Functionally
Imperative Programming
Generally, we have two ways of thinking about implementing a system. One is focused on how to implement it, such as cooking. Usually, you follow the cooking method you are familiar with: first wash the vegetables, then cut the vegetables, Heat the oil, serve, and then... This looks like a series of orders. We call this "how to do" programming style imperative programming. Its characteristics are very similar to the assembly line of a factory and the instruction processing of a computer, both of which are serialized and imperative.
CookingTask cookingTask = new CookingTask(); cookingTask.wash(); cookingTask.cut(); cookingTask.deepFry(); cookingTask.fried(); ...
Declarative programming
There is another way you are concerned about what to do. If we use lambda and functional expression to solve the above problem, it should be Like this:
public class CookingDemo { public void doTask(String material, Consumer<String> consumer) { consumer.accept(material); } public static void main(String[] args) { CookingDemo cookingDemo = new CookingDemo(); cookingDemo.doTask("蔬菜", material -> System.out.println("清洗" + material)); cookingDemo.doTask("蔬菜", material -> System.out.println(material + "切片")); cookingDemo.doTask("食用油", material -> System.out.println(material + "烧热")); cookingDemo.doTask("", material -> System.out.println("炒菜")); } }
Here we leave the implementation details of cooking to the function library. Its biggest advantage is that you read it like a problem statement. Using this We can quickly understand its function. When you add other steps to the cooking process, it becomes very simple. You only need to call the doTask method to pass the materials in for processing. For example, I want to beat an egg before the cooking oil is heated.
cookingDemo.doTask("鸡蛋", material -> System.out.println(material + "打碎搅拌均匀"));
Instead of writing a method to handle eggs.
What is functional programming
The simplest answer to the question "What is functional programming" is "It is a A way of programming using functions". Everyone's understanding is different. The core is: when thinking about problems, use immutable values and functions. The functions process one value and map it to another value.
Different language communities often have exclusive admiration for the characteristics of their respective languages. It's too early to talk about how Java programmers define functional programming, but it doesn't matter at all! We care about writing good code, not code that conforms to a functional programming style.
Let's imagine designing a function that inputs a string type and Boolean type parameters and outputs an integer parameter.
int pos = 0; public Integer foo(String str, boolea flag){ if(flag && null != str){ pos++; } return pos; }
This example has input and output, and each call may also update the value of an external variable. We call such a function a function with side effects.
In the context of functional programming, a "function" corresponds to a mathematical function: it accepts zero or more arguments, produces one or more results, and has no side effects. You can think of it as a black box which takes input and produces some output like the following function
public Integer foo(String str, boolea flag){ if(flag && null != str){ return 1; } return 0; }
This type of function is the same as what you have in Java programming language The difference between the functions we see is very important (we cannot imagine that mathematical functions such as log or sin have side effects). In particular, when a mathematical function is called with the same parameters, the result it returns must be the same. Here, we will not consider methods like Random.nextInt for the moment.
Side effects of functions
When talking about "functional", we think What it actually says is "like a mathematical function - no side effects." From this, some subtle problems in programming arise. Do we mean that every function can only be built using functions and mathematical ideas like if-then-else? Or do we also allow some non-functional operations to be performed inside functions, as long as the results of these operations are not exposed to other parts of the system? In other words, if the program has certain side effects, but these side effects will not be perceived by other callers, can we assume that this side effect does not exist? The caller doesn't need to know about, or care about, these side effects because it has absolutely no effect on it.
When we wish to define the difference between the two, we call the first purely functional programming and the latter functional programming.
In actual programming, it is difficult for us to use Java language to complete a program in a purely functional way, because many old codes, including standard library functions, have side effects (calling Scanner.nextLine has side effects, it will Read a line from a file, usually the results of two calls are completely different). You want to write a nearly purely functional implementation of your system, and you need to make sure that your code has no side effects. Assume that such a function or method has no side effects. When entering the method body for execution, the value of a field will be incremented by one, and before exiting the method body, the value of the field will be decremented by one. For a single-threaded program, this method has no side effects and can be regarded as a functional implementation.
Our guideline for constructing functional style is that functions or methods called "functional style" can only modify local variables. In addition, the objects it refers to should be final. All reference type fields point to immutable objects.
Summarize
The above is the detailed content of Example explanation of functional programming in Java8. For more information, please follow other related articles on the PHP Chinese website!