Often technical jargon can be ambiguous and mislead developers, a perfect example of this is the term “functional programming” (FP) or “Object oriented programming ” (OOP). It’s easy to assume that FP is just writing your code in a series of functions but its much more meaningful then that.
🤔 What is functional programming?
Functional Programming is the use of Pure Functions to create extremely explicit and easily testable code. By avoiding sharing/mutating state and reducing side-effects FP lowers the cognitive burden of adding functionality to a growing code base.
⏸️ Pause for definitions!
Pure Functions: A function that takes a set of inputs and provides an output. The mapping of input/output is
Sharing State: When multiple you have several scopes that share variables rather then pass them as arguments.
Mutating State: When you modify a variables value directly rather then create a new variable.
You may be skeptical about why sharing state can be bad, or why you want to write “pure functions”. Pure functions make testing easier, any good codebase has tests and when maintaining tests you want to make sure your testing all possible code paths the user can go down. Pure functions by definition have a set range of inputs and outputs which make writing tests straight forward, alternatively if your method is using global state you now must consider everywhere that state is accessed or changed to ensure that it doesn’t change part way through your function execution.
🧠 How to make your code as functional as possible
Many modern frameworks like React have embraced FP and made it much harder to shoot yourself in the foot but there are still some tenets of FP you want to keep in mind.
1. State History
Mutating state means you lose history of that change, you should avoid mutating any variables if possible.
2. Encapsulate Side-effects
Side effects represent implicit behaviors in your code and this makes your functions hard to test and even harder to troubleshoot.
Once you go through the work of writing and testing a pure function it should be used in as many places as possible, this means accepting a wide variety of types. It’s much better to have a single method that can handle a generic type then a different method for every different type you make going forward.
Unless you have been explained exactly what it means (and how it compares to other types of programming) you may assume it just means “writing functions”. If any of this article was unclear I highly recommend checking out this Introduction to functional programming article by OpenSource. I would also encourage you to read my article about another programming paradigm “Object oriented programming” here!
If you enjoyed this please follow my blog or subscribe to my newsletter.
Have a great day!