为什么函数式编程很好? [英] Why is functional programming good?

查看:80
本文介绍了为什么函数式编程很好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到有很多函数式编程狂热者坚持的某些核心概念:


  • 避免状态避免使用可变数据

  • 减少副作用


  • etc ...




  • 我不只是想知道其他的东西进行函数式编程,但为什么这些核心思想是好的?为什么它是好的,以避免状态,其余?

    解决方案

    简单的答案是,如果你没有额外的状态担心,你的代码更容易推理。简单的代码更容易维护。您无需担心特定代码片段(如函数)之外的事情来修改它。这对测试等事情有非常有用的影响。如果你的代码不依赖于某个状态,那么为该代码创建自动化测试就容易多了,因为你不需要担心初始化某些状态。

    使用无状态代码可以更容易地创建线程化程序,因为您无需担心两个执行线程修改/读取共享数据片段同一时间。你的线程可以运行独立的代码,这可以节省大量的开发时间。



    实质上,避免状态会创建更简单的程序。从某种意义上说,移动部分的数量较少(即代码行可以交互),所以这通常意味着代码更加可靠并且包含更少的错误。基本上,代码越简单,越不会出错。对我来说,这是编写无状态代码的本质。



    创建无状态的功能代码有很多其他原因,但它们都归结为简单对我来说。


    I've noticed that there are certain core concepts that a lot of functional programming fanatics cling to:

    • Avoiding state

    • Avoiding mutable data

    • Minimizing side effects

    • etc...

    I'm not just wondering what other things make functional programming, but why these core ideas are good? Why is it good to avoid state, and the rest?

    解决方案

    The simple answer is that if you don't have extra state to worry about, your code is simpler to reason about. Simpler code is easier to maintain. You don't need to worry about things outside a particular piece of code (like a function) to modify it. This has really useful ramifications for things like testing. If your code does not depend on some state, it becomes much easier to create automated tests for that code, since you do not need to worry about initializing some state.

    Having stateless code makes it simpler to create threaded programs as well, since you don't need to worry about two threads of execution modifying/reading a shared piece of data at the same time. Your threads can run independent code, and this can save loads of development time.

    Essentially, avoiding state creates simpler programs. In a way, there's less "moving parts" (i.e., ways lines of code can interact), so this will generally mean that the code is more reliable and contains less faults. Basically, the simpler the code, the less can go wrong. To me this is the essence of writing state-less code.

    There are plenty of other reasons to create stateless, "functional" code, but they all boil down to simplicity for me.

    这篇关于为什么函数式编程很好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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