Functional programming (often abbreviated FP) is the process of building software by composing pure functions, avoiding shared state, mutable data, and side-effects. Functional programming is declarative rather than imperative, and application state flows through pure functions. Contrast with object oriented programming, where application state is usually shared and co-located with methods in objects.
It is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changingstate and mutable data.
More importantly, the functions developed in this style of programming evaluate like a mathematical formula. So if you provide the same input to the function multiple times, the function will evaluate the same output every time.
Is functional programming new?
Nope, it has been around since the 1950’s but due to the speed of the computer it was not fully developed at that time. Over the years it has gained popularity most likely out of frustration in maintaining and updating software. It has its roots in lambda calculus.
Why learn functional programming?
- To eliminate errors in your software
- To make your code more transportable by eliminating the need to execute your code in a specific sequence.
- To eliminate side effects or changes in state that do not depend on the function inputs. For example if this function is removed without affecting other expressions. This leads to better understanding and predictability of the function.
What are some features of FP(Functional Programming)?
- First-Class Functions – Store functions into a variable
- High-Order Functions – Functions can return other functions
- Pure Functions – Functions that do not change value based upon the environment.
- Closures – This means you can save data inside of a function that’s only accessible to a specific returning function.
- Immutable State – State of the object can never change
Use case for using functional programming: Object Mutability
- Say you have an object that is passed through a function and is modified in that function.
- Now, the resulting object differs from the input object.
- If the resulting object is utilized in other functions, now you have modified those functions and the tracking of those changes on that object becomes more difficult to follow
Use case for functional programming: User Management
Goal
To be able to add, read, delete, and update a username and password using the object in memory.
Required Functions:
- Add User
- Read User
- Delete User
- Change User
Potential Problems:
- Race conditions where the save function executes after the user updates their profile which then initiates another save. If they happen out of order then the update to the profile could be overwritten by the original save.
- Shared State where the order in which the function calls happen is important.