为什么我们在编码时需要避免突变?什么是突变? [英] Why do we need to avoid mutations while coding? What is a mutation?

查看:75
本文介绍了为什么我们在编码时需要避免突变?什么是突变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么第二个代码(带有流的代码)比第一个更好的解决方案?

Why is the second code (the one with the stream) a better solution than the 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;

   }

第二个:

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

推荐答案

静音正在更改对象,并且是编程语言中的常见副作用之一.

Mutation is changing an object and is one common side effect in programming languages.

具有功能合同的方法将始终为相同的参数返回相同的值,并且没有其他副作用(例如存储文件,打印,读取).因此,即使您在函数内部对临时值进行了变异,从外部来看,它仍然是纯净的.通过将第一个示例放入函数中进行演示:

A method that has a functional contract will always return the same value to the same arguments and have no other side effects (like storing file, printing, reading). Thus even if you mutate temporary values inside your function it's still pure from the outside. By putting your first example in a function demonstrates it:

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

纯函数方法甚至不更新局部变量.如果将第二个版本放在函数中,那将是纯粹的:

A purely functional method doesn't even update local variables. If you put the second version in a function it would be pure:

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

对于一个了解其他语言的人来说,这是很自然的事情,他们长期以来一直偏爱mapreduce以及lambda的功能样式.这两个版本都易于阅读和测试,这是最重要的部分.

For a person that knows other languages that has long been preferring a functional style map and reduce with lambda is very natural. Both versions are easy to read and easy to test, which is the most important part.

Java具有功能类. java.lang.String是其中之一.

Java has functional classes. java.lang.String is one of them.

这篇关于为什么我们在编码时需要避免突变?什么是突变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆