无状态编程的优势? [英] Advantages of stateless programming?

查看:25
本文介绍了无状态编程的优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在学习函数式编程(特别是 Haskell,但我也学习了关于 Lisp 和 Erlang 的教程).虽然我发现这些概念非常有启发性,但我仍然没有看到无副作用"概念的实际方面.它的实际优势是什么?我试图以函数式思维方式思考,但有些情况似乎过于复杂,而且无法以简单的方式保存状态(我不认为 Haskell 的 monad 是简单的").

I've recently been learning about functional programming (specifically Haskell, but I've gone through tutorials on Lisp and Erlang as well). While I found the concepts very enlightening, I still don't see the practical side of the "no side effects" concept. What are the practical advantages of it? I'm trying to think in the functional mindset, but there are some situations that just seem overly complex without the ability to save state in an easy way (I don't consider Haskell's monads 'easy').

是否值得继续深入学习 Haskell(或另一种纯函数式语言)?函数式或无状态编程实际上比过程式编程更有效率吗?以后有没有可能继续使用Haskell或者其他函数式语言,还是只为了理解而学习?

Is it worth continuing to learn Haskell (or another purely functional language) in-depth? Is functional or stateless programming actually more productive than procedural? Is it likely that I will continue to use Haskell or another functional language later, or should I learn it only for the understanding?

我关心的不是性能而是生产力.所以我主要是问我使用函数式语言是否会比使用过程/面向对象/其他语言更高效.

I care less about performance than productivity. So I'm mainly asking if I will be more productive in a functional language than a procedural/object-oriented/whatever.

推荐答案

阅读 函数式编程简介.

无状态编程有很多优点,尤其是戏剧性多线程和并发代码.说白了,可变状态是多线程代码的敌人.如果默认值是不可变的,程序员就不需要担心一个线程会改变两个线程之间共享状态的值,因此它消除了与竞争条件相关的一整类多线程错误.由于不存在竞争条件,因此也没有理由使用锁,因此不变性也消除了另一类与死锁相关的错误.

There are lots of advantages to stateless programming, not least of which is dramatically multithreaded and concurrent code. To put it bluntly, mutable state is enemy of multithreaded code. If values are immutable by default, programmers don't need to worry about one thread mutating the value of shared state between two threads, so it eliminates a whole class of multithreading bugs related to race conditions. Since there are no race conditions, there's no reason to use locks either, so immutability eliminates another whole class of bugs related to deadlocks as well.

这就是函数式编程很重要的重要原因,并且可能是跳上函数式编程火车的最佳原因.还有许多其他好处,包括简化调试(即函数是纯的并且不会改变应用程序其他部分的状态)、更简洁和富有表现力的代码、与严重依赖设计模式的语言相比更少的样板代码,以及编译器可以更积极地优化您的代码.

That's the big reason why functional programming matters, and probably the best one for jumping on the functional programming train. There are also lots of other benefits, including simplified debugging (i.e. functions are pure and do not mutate state in other parts of an application), more terse and expressive code, less boilerplate code compared to languages which are heavily dependent on design patterns, and the compiler can more aggressively optimize your code.

这篇关于无状态编程的优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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