编写程序,为什么e的值不变_利用“不变性”的力量编写更安全,更清洁的代码...

编写程序,为什么e的值不变

by Guido Schmitz

由Guido Schmitz

利用“不变性”的力量编写更安全,更清洁的代码 (Write safer and cleaner code by leveraging the power of “Immutability”)

Immutability is one of the building blocks of functional programming. It allows you to write safer and cleaner code. I’ll show you how you can achieve immutability through some JavaScript examples.

不变性是功能编程的组成部分之一。 它使您可以编写更安全,更干净的代码。 我将通过一些JavaScript示例向您展示如何实现不变性。

According to Wikipedia (source):

根据维基百科( 来源 ):

An immutable object (unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created. In some cases, an object is considered immutable even if some internally used attributes change but the object’s state appears to be unchanging from an external point of view.
不变对象(不变对象)是创​​建后状态无法修改的对象。 这与可变对象(可变对象)相反,可变对象在创建后可以进行修改。 在某些情况下,即使某些内部使用的属性发生了变化,但从外部角度看,该对象的状态似乎没有变化,该对象仍被视为不可变的。

不变数组 (Immutable Arrays)

Arrays are a good starting point to get a grasp of how immutability actually works. Lets take a look.

数组是了解不变性实际上是如何工作的一个很好的起点。 让我们来看看。

const arrayA = [1, 2, 3];arrayA.push(4); const arrayB = arrayA;arrayB.push(5); console.log(arrayA); // [1, 2, 3, 4, 5]console.log(arrayB); // [1, 2, 3, 4, 5]

This example assigns arrayB to a reference of arrayA, so the push method adds the value 5 into both variables. Our code mutates other values indirectly, which is not what we want to do. This violates the principle of immutability.

此示例受让人arrayBarrayA的基准,故推动方法将值5到两个变量。 我们的代码间接地改变了其他值,这不是我们想要做的。 这违反了不变性原则。

We can improve our example to be immutable by using the slice function, and the behavior of the code is different.

我们可以使用slice函数将示例改进为不可变的,并且代码的行为也有所不同。

const arrayA = [1, 2, 3];arrayA.push(4); const arrayB = arrayA.slice(0);arrayB.push(5); console.log(arrayA); // [1, 2, 3, 4]console.log(arrayB); // [1, 2, 3, 4, 5]

This is exactly what we want. The code doesn’t mutate the other values.

这正是我们想要的。 该代码不会更改其他值。

Remember: When using push to add a value to an array, you are mutating the array. You want to avoid mutating variables because it can cause side effects in your code. The slice function returns a copy of the array.

切记:使用push向数组添加值时,您是在对数组进行突变 。 您要避免突变变量,因为它可能在代码中引起副作用。 slice函数返回数组的副本。

功能 (Functions)

Now you know how to avoid mutating other values. How would you write functions to be “pure”? Pure is another word to call a function that doesn’t have any side effects and will not change state.

现在您知道了如何避免变异其他值。 您如何将函数编写为“纯”的? Pure是调用没有任何副作用且不会更改状态的函数的另一个词。

Let’s look at a function that leverages the same principle from the arrays example. First we create a function that mutates another value, then we improve the function to be “pure”.

让我们来看一个利用数组示例中相同原理的函数。 首先,我们创建一个变异另一个值的函数,然后将其改进为“纯”。

const add = (arrayInput, value) => {  arrayInput.push(value);   return arrayInput;};
const array = [1, 2, 3]; console.log(add(array, 4)); // [1, 2, 3, 4]console.log(add(array, 5)); // [1, 2, 3, 4, 5]

So again, we are mutating our input which creates an unpredictable function. In the functional programming world, there is a golden rule around functions: a function with the same input should always return the same result.

同样,我们正在改变我们的输入,从而创建了一个不可预测的函数。 在函数式编程世界中,函数周围有一条黄金法则: 具有相同输入的函数应始终返回相同的结果

The function above violates the golden rule. Every time our add function is called, it mutates the array variable and the result is different.

上面的功能违反了黄金法则。 每次调用我们的add函数时,它都会对数组变量进行突变,结果会有所不同。

Let’s see how we can change the implementation of our add function so it’s immutable.

让我们看看如何更改add函数的实现,使其不变。

const add = (arrayInput, value) => {  const copiedArray = arrayInput.slice(0);  copiedArray.push(value);   return copiedArray;}; const array = [1, 2, 3];
const resultA = add(array, 4);console.log(resultA); // [1, 2, 3, 4]
const resultB = add(array, 5);console.log(resultB); // [1, 2, 3, 5]

Now we can call our function multiple times, and expect the output to be the same, based on the input. This is because we are no longer mutating the array variable. We can call this function a “pure function”.

现在,我们可以多次调用函数,并期望基于输入的输出是相同的。 这是因为我们不再对数组变量进行变异。 我们可以将此函数称为“纯函数”。

Note: You can also use concat, instead of slice and push.

注意:您也可以使用concat ,而不是slicepush

We can use the spread syntax, available in ES6, to shorten this function.

我们可以使用ES6中可用的传播语法来缩短此功能。

const add = (arrayInput, value) => […arrayInput, value];

并发 (Concurrency)

NodeJS applications use a concept called concurrency. A concurrent operation means that two computations can both make progress regardless of the other. If there are two threads, the second computation doesn’t need to wait for the completion of the first one in order to advance.

NodeJS应用程序使用称为并发的概念。 并发操作意味着两个计算都可以进行而与另一个无关。 如果有两个线程,则第二个计算不需要等待第一个计算完成就可以继续。

NodeJS makes concurrency possible with the event-loop. The event-loop repeatedly takes an event and fires any event handlers listening to that event one at a time. This model allows a NodeJS application to process a huge amount of requests. If you want to learn more, read this article about the event-loop.

NodeJS通过事件循环使并发成为可能。 事件循环反复获取一个事件,并一次触发所有侦听该事件的事件处理程序。 该模型允许NodeJS应用程序处理大量请求。 如果您想了解更多信息,请阅读有关事件循环的文章

What does immutability have to do with concurrency? Since multiple operations can change a value outside of the function’s scope in a concurrent way, this creates unreliable output and causes unexpected results. Be aware of a function that mutates variables outside of its scope, as this can be really dangerous.

不变性与并发性有什么关系? 由于多个操作可以并发方式更改函数范围之外的值,因此这将导致输出不可靠并导致意外结果。 请注意,一个函数会在其作用域之外对变量进行变异,因为这确实很危险。

下一步 (Next steps)

Immutability is an important concept to understand on your journey to learn functional programming. You might want to take a look at ImmutableJS, written by developers at Facebook. The library provides certain immutable data structures like Map, Set, and List.

不变性是学习函数式编程的重要概念。 您可能想看看由Facebook开发人员编写的ImmutableJS 。 该库提供了某些不变的数据结构,例如MapSetList

Immutable.js, persistent data structures and structural sharingWhy use Immutable.js instead of normal JavaScript object?medium.comHigher Order Functions: Using Filter, Map and Reduce for More Maintainable CodeHigher order functions can help you to step up your JavaScript game by making your code more declarative. That is…medium.freecodecamp.org

Immutable.js,持久数据结构和结构共享 为什么使用Immutable.js代替普通JavaScript对象? medium.com 高阶函数:使用过滤器,映射 和约简 以获得更可维护的代码 高阶函数可通过使代码更具声明性来帮助您增强JavaScript游戏。 那是… medium.freecodecamp.org

Click the ? below so other people will see this article here on Medium. Thanks for reading.

点击 ? 下面,其他人会在Medium上看到此文章。 谢谢阅读。

翻译自: https://www.freecodecamp.org/news/write-safer-and-cleaner-code-by-leveraging-the-power-of-immutability-7862df04b7b6/

编写程序,为什么e的值不变

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值