what’s pure function ?
Pure function
arguments not change
不修改传递给它们的参数
always return the same set of arguments according to the arguments
总是能根据传进来的参数返回对应唯一的结果
it doesn’t mutate any data and it doesn’t have any side effects.
对外部是没有影响的(网络请求、更新数据库等…),不会导致任何外部数据的变动
如下 是计算一个产品价格和关税一起的费用的函数:
function priceAfterTax(productPrice) { return (productPrice * 0.20) + productPrice; }
priceAfterTax()
没有改变参数productPrice
;满足(1)
返回一个新的结果,并且根据参数始终能保证相同的结果。即使几万次相同的输入,返回的结果也是相同的;满足(2)
对函数外的数据等没有任何影响;满足(3)
所以,这是一个Good Pure Function
。
Impure function
change the arguments. like network or database calls.
可以修改参数,进行网络请求、数据库操作等
比较一下两者
let tax = 20;
let val = 100;
function impureFunc(value){
return (productPrice * tax / 100) + productPrice;
}
function pureFunc(value){
return (productPrice * 0.20) + productPrice;
}
pureOutput = pureFunc(val);
impureOutput = impureFunc(val);
console.log("Impure result: " + impureOutput); // result is uncertain however input is same.
console.log("Pure result: " + pureOutput); // result is consistent with same input
这里我们可以清晰地看到:impureFunc()
违背了第(2)条规则,
因为tax
是外部的,是会随时变动的,这就导致了返回结果对于同样的输入,有可能不唯一。
Why Using Pure Function ?
One of the major benefits of using pure functions is they are immediately testable. They will always produce the same result if you pass in the same arguments.
They also makes maintaining and refactoring code much easier.
使用纯函数最大的好处就是它们便于立刻测试,不需要书写玩整段代码,写完一个纯函数就可以马上测试。
因为根据第(2)条规则,纯函数总能根据传入参数返回相同的结果。
而这也使得代码在工程上整体变得易于维护和重构。
注:函数式编程、Redux
都需要使用pure function
,作为根基,值得大家深入学习理解,
另外熟练使用纯函数和非纯函数混合开发编程,那就再好不过了。