神刀安全网

Pure vs. Impure Functions

Like many others, Francois Ward’s “ State of the Art JavaScript in 2016 ″ article caught my attention recently. Having departed Laurel & Wolf for some time now, where React and Redux played a central role in our front-end architecture, I had always wished I had the same degree of understanding of that area of the codebase as I did in my area of go-to expertise, the API.

Genius former colleagues of mine like Scott Corgan would speak from time to time about what I knew must’ve been a simple, yet important distinction. To be honest, despite his excellent, and numerous explanations, it took awhile before I understood what a pure function really was, and more importantly, why it matters.

In Redux, almost all of the moving parts are pure functions. There is one centralized store and source of truth. Reducer functions are responsible for manipulating data that makes up the store. Everything is much clearer than in vanilla Flux.

Francois Ward

To be honest, you can really only get so far in learning about Redux without understanding the difference between pure and impure functions. A pure function is defined by the following two requirements:

1. The return values of the function may depend only upon the value of the arguments passed to the function.

2. The function may not have side effects like network or database calls.

That is it. There is nothing else to understand about the difference in definition between a pure and impure function.

https://gist.github.com/kulte/7c44300d85d6c9b4f3446f8b23022b75.js

The distinction becomes an important one in Redux, because Redux requires that certain functions be pure. But why is this the case? What this actually buys you is not the easiest thing to see right off the bat. Reducer functions in Redux have to be pure because by doing so, your state tree is predictable . Heck, the tagline for the Redux project is that “Redux is a predictable state container for JavaScript apps.” This all helps you to write complex JavaScript applications that behave consistently and are easy to test. Since the reducer function cares only about the current state and the action being dispatched, it becomes easy for developers to predict how the state will change as a result of a given action being dispatched, and it becomes really simple to write good unit tests. 

Now your side effects, such as API calls, do need to go somewhere, but in a reducer is not that place. This touches on some (only slightly) more advanced uses of Redux and is out of scope for this blog post.

If you have anything to correct and/or add, or would like to suggest other areas of Redux for future blog posts that you are interested in learning about, please feel free to tweet @_kulte or email me at zafriedman at gmail dot com .

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Pure vs. Impure Functions

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮