Why Functional Programming?

Why Functional Programming?

Why Static Type?

  • 性能 - 方法调用速度更快,因为不需要在运行时才来判断调用的是哪个方法。
  • 可靠性 - 编译器验证了程序的正确性,因而运行时崩溃的概率更低。
  • 可维护性 - 陌生代码更容易维护,因为你可以看到代码中用到的对象的类型。
  • 工具支持 - 静态类型使 IDE 能提供可靠的重构、精确的代码补全以及其他特性。

Benefit of Functional Programming

  • 头等函数 - 把函数(一小段行为)当作值使用,可以用变量保存它,把它当作参数传递,或者当作其他函数的返回值。
  • 不可变性 - 使用不可变对象,这保证了它们的状态在其创建之后不能再变化。
  • 无副作用 - 使用的是纯函数。此类函数在输入相同时会产生同样的结果,并且不会修改其他对象的状态,也不会和外面的世界交互。

Moving Parts

  • 简洁

函数式风格的代码 比相应的命令式风格的代码更优雅、更简练,因为把函数当作值可以让你获得更强大的抽象能力,从而避免重复代码。

假设你有两段类似的代码,实现相似的任务但具体细节略有不同,可以轻易地将这段逻辑中公共的部分提取到一个函数中,并将其他不同的部分作为参数传递给它。这些参数本身也是函数,但你可以使用一种简洁的语法来表示这些匿名函数,被称作 lambda 表达式。

  • 多线程安全

多线程程序中最大的错误来源之一就是,在没有采用适当同步机制的情况下,在不同的线程上修改同一份数据。如果你使用的是不可变数据结构和纯函数,就能保证这样不安全的修改根本不会发生,也就不需要考虑为其设计复杂的同步方案。

  • 测试更加容易

没有副作用的函数可以独立地进行测试,因为不需要写大量的设置代码来构造它们所依赖的整个环境。

Functional programming, views a program as a mathematical function which is evaluated to produce a result value. That function may call upon nested functions, which in turn may call upon more nested functions. A nested function evaluates to produce a result. From there, that result is passed on to the enclosing function, which uses the nested function values to calculate its own return value. To enable functions to easily pass data to and from other functions, functional programming languages typically define data structures in the most generic possible way, as a collection of (any) things. They also allow functions to be passed to other functions as if they were data parameters. A function in this paradigm is not allowed to produce any side effects such as modifying a global variable that maintains state information. Instead, it is only allowed to receive parameters and perform some operations on them in order to produce its return value. Executing a functional program involves evaluating the outermost function, which in turn causes evaluation of all the nested functions, recursively down to the most basic functions that have no nested functions.

Why is functional programming a big deal?

  • Clarity

Programming without side effects creates code that is easier to follow - a function is completely described by what goes in and what comes out. A function that produces the right answer today will produce the right answer tomorrow. This creates code that is easier to debug, easier to test, and easier to re-use.

  • Brevity

In functional languages, data is implicitly passed from a nested function to its parent function, via a general-purpose collection data type. This makes functional programs much more compact than those of other paradigms, which require substantial “housekeeping” code to pass data from one function to the next.

  • Efficiency

Because functions do not have side effects, operations can be re-ordered or performed in parallel in order to optimize performance, or can be skipped entirely if their result is not used by any other function.

References