First introduction to functional programming | Functional programming

hi~ I am 无言非影, very happy to share my learning journey here. Some notes compiled
about functional programming are all recorded in: Functional Programming Column


What are the benefits of functional programming?

  • Functional programming can abandon this
  • During the packaging process, three-sharking can be better used to filter out useless code.
    • Tree-shaking comes from rollup.js. The principle is the same, which is to eliminate unused code by analyzing static ES modules.
  • Convenient for testing and parallel processing
  • You can use many libraries to help functional development: lodash , underscore , ramda
  • Functional programming is receiving more and more attention with the popularity of React. Vue3 has also begun to embrace functional programming.

Common programming paradigms

  • Procedural programming/Imperative programming
    • Procedural languages ​​are suitable for solving linear algorithmic problems, emphasizing the "top-down" and "excellence" design methods.
  • event driven programming
    • Event-driven is often used for user-program interaction through graphical user interfaces (mouse, keyboard, touchpad). Of course, it can also be used to handle exceptions and respond to user-defined events, etc.
  • Object-oriented OOP
    • Object-oriented programming includes three basic concepts: encapsulation, inheritance, and polymorphism. Object-oriented languages ​​support the object-oriented programming paradigm through classes, methods, objects, and message passing.
  • functional programming
    • Functional programming means avoiding the use of shared state (Shared State), mutable state (Mutable Data), and side effects (Side Effects) in software development projects.

Two programming paradigms commonly used in JS

  • Prototypal Inheritance (OOP): Prototype Chain
  • Functional programming: closure, first-class function

Definition of functional programming

Functional Programming (Functional Programming), abbreviation FP, is a programming paradigm and a programming style, which is in parallel relationship with object-oriented.
It can be considered a kind of 思维模式+实现方法.
The way of thinking is to abstract things and the connections between things in the real world into the program world 是对运算过程的一种抽象.

  • The core of functional programming is programming using only pure mathematical functions , 函数的结果仅取决于参数,而没有副作用like I/O or state transitions.
    • I/O(English: Input/Output), that is, input/output, usually refers to the input and output of data between memory (internal and external) or other peripheral devices, and is the relationship between an information processing system (such as a computer) and the external world (which may be a human or communication between another information processing system). Inputs are the signals or data that a system receives, and outputs are the signals or data that are sent from it.

The difference between functional programming and object-oriented programming

Object-Oriented Programming

  • Advantages : Imperative coding style, code is easy to read, like a direct set of instructions that the computer can easily follow.
  • Disadvantages : Object-oriented programming often requires shared state, which can easily cause race condition vulnerabilities (for example, bugs that may occur when several functions call the same batch of resources on the prototype chain).

functional programming

  • Advantages : No need to worry about shared state or side effects, combining code into more reusable code, "point-free style" (also called implicit programming), using pure functions, no need to worry about thread resource conflicts, Issues like race conditions.
  • Disadvantages : If the code overuses functional programming features (such as parameter-less style and combination of a large number of methods), it will affect its readability, resulting in more conciseness but less readability.

Functional programming thinking

  • The essence of a program: Obtain corresponding output through some operation based on input. There are many input and output functions involved in the program development process.
  • The function in functional programming does not refer to the function in the program, but the function in mathematics, that is, the mapping relationship. For example: y=sin(x), which is the relationship between x and y
  • Get the same output when given the same input (pure function)
  • Functional programming describes the mapping between data (functions)
// 传统的过程式编程,可能这样写:
  let a = 1 + 2;
  let b = a * 3;
  let c = b - 4;
// 函数式编程要求使用函数,我们可以把运算过程定义为不同的函数,然后写成下面这样:
  let result = subtract(multiply(add(1,2), 3), 4);

Five characteristics of functional programming

  • Functions are "first class citizens"
    • In JS, a function is an ordinary object. We can store the function in a variable/array. It can also be used as a parameter and return value of another function, or by building a constructor new Function().
  • Only use "expression" instead of "statement"
    • "Expression" (expression) is a simple operation process, which always returns a value; "statement" (statement) performs a certain operation and has no return value.
    • In functional programming 表达式"(expression), each step is a simple operation and has a return value.
  • no side effects"
    • The so-called "side effect" refers to the interaction between the inside and outside of a function (the most typical case is to modify the value of a global variable), producing results other than operations.
    • Functional programming emphasizes that there are no "side effects", which means that the function must remain independent. All functions are to return a new value and have no other actions, especially the values ​​of external variables must not be modified.
      let list = ["a", "b"] 
      // 纯函数 - 没有副作用, 对于相同的函数,输出是一样的
      
      // slice方法,截取的时候返回截取的函数,不影响原数组
      list.slice(0, 2) // =>  ["a", "b"]
      list.slice(0, 2) // => ["a", "b"]
      
      // 不纯的函数 - 有副作用,对于相同的输入,输出是不一样的
      
      // splice方法,返回原数组,改变原数组
      list.splice(0, 2) // =>  ["a", "b"] 
      list.splice(0, 2) // => []
      
  • Do not modify status
    • Functional programming only returns new values ​​and does not modify system variables.
    • Functional programming uses parameters to save state
    无状态其实就是不做数据持久化(写入数据库或缓存),一个功能模块的输入和输出应仅由函数的参数和返回值定义。因为如果你在这个函数里对数据做了持久化,那就相当于对系统做了个隐藏的输出,从函数定义上是看不出来的,无异于增加编码人员的心智负担,同时也可能出现各种数据并发引起的异常情况。
    
  • referential transparency
    • Referential transparency (Referential transparency) means that the operation of the function does not depend on external variables or "state", but only depends on the input parameters. As long as the parameters are the same at any time, the return value obtained by referencing the function is always the same.

appendix

Guess you like

Origin blog.csdn.net/weixin_40887836/article/details/118408673