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

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

问题描述

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

是否值得继续深入学习Haskell(或另一种纯粹的函数式语言)?功能性或无状态编程实际上比程序更高效?我很可能会在以后继续使用Haskell或其他函数式语言,或者我应该只是为了理解而学习它?



我不关心性能而是关注生产力。所以我主要问的是,在功能性语言中,我是否会比程序/面向对象/任何东西更有效率。

解决方案

阅读函数式编程



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



这就是为什么函数编程很重要,并且可能是跳过功能性编程序列的最佳选择。还有很多其他好处,包括简化的调试(即,功能是纯粹的,不会在应用程序的其他部分中改变状态),与代码严重依赖于设计模式的语言相比,更简洁和表达的代码,更少的样板代码,以及编译器可以更积极地优化您的代码。


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').

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.

解决方案

Read Functional Programming in a Nutshell.

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天全站免登陆