Java – why do we need to avoid mutations in coding? What is mutation?

Why is the second code (code with flow) better than the first code?

First:

public static void main(String [] args) {
   List<Integer> values = Arrays.asList(1,2,3,4,5,6);
   int total = 0;
   for(int e : values) {
       total += e * 2;

   }

Second:

System.out.println(total);
   System.out.println(
           values.stream()
           .map(e-> e*2)
           .reduce(0,(c,e)-> c + e));

Solution

Variation is changing an object and is a common side effect in programming languages

Methods with function contracts will always return the same value to the same parameters without other side effects (such as storing files, printing, reading) Therefore, even if you change the temporary value in your function, it is still purely external Demonstrate it by putting your first example in a function:

public static int squareSum(const List<Integer> values)
{
    int total = 0;
    for(int e : values) {
        total += e * 2;  // mutates a local variable
    }
    return total;
}

Pure function methods do not even update local variables If you put the second version in a function, it will be pure:

public static int squareSum(const List<Integer> values)
{
    return values.stream()
           .map(e-> e*2)
           .reduce(0,e)-> c + e);
}

For someone who knows other languages, it's natural to prefer functional style maps for a long time and use lambda Both versions are easy to read and easy to test, which is the most important part

Java has function classes java. Lang. string is one of them

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>