DEV Community

Discussion on: Explain functional programming paradigm Like I'm Five

Collapse
 
kspeakman profile image
Kasey Speakman • Edited

FP is just using types (data structures) and functions to solve problems. Like anything, it requires practice to do well.

If you understand procedural programming, you can start with that understanding. But where procedures encourage you to pass data into another procedure to be modified, functions expect input data (which will not be modified) and return output data. Much like electronic circuits have dedicated input and output pins/leads. FP also adds several capabilities over procedural.

  • Immutability by default
  • Pass functions as arguments in the same way you pass data as arguments
  • Call a function with an incomplete parameter list (partial application)
    • This creates a new function that only needs the parameters you didn't provide
  • Sum types, which allow you to say "either this data structure OR that data structure but not both".
  • Pattern matching, especially for sum types, allows you to choose different behavior (functions) for different kinds of inputs.

Versus OO, the primary difference is that OO objects bind data and behavior together. Using the traditional OO organizational technique of inheritance, this can lead to hard-to-resolve conflicts of behavior or data structure. This in turn leads to all manner of OO guiding principles including SOLID. However, FP keeps data and behavior (functions) separate. So you can compose data types with other data types and functions with other functions without much fuss. Types act as a contract between functions. And functions simply transform input into output.

Up to now I have assumed pure transformation functions (only converting input to output, no side effects such as printing to screen), as these are the easiest to understand and test in isolation. You want as much of your program as possible to be made of these. But at some point, you have to perform side effects. This is best done "at the edges" of your program. Personally I like to declare side effects as data (whatever data is needed to perform it), so the inner core of my app can return the side effect as plain data. Then I have an effect function at the edge which takes the declared side effect and actually performs it.

Here is a relevant video.