I have become more interested in Functional Programming recently. It is a complex topic that requires a mindshift and different coding style. So I am just going to focus on the basics, to setup the other posts in this series.
Functional Programming is about passing data between functions, rather than having an object like a class instance which knows about its own data (state) and methods.
Here are some of the main ideas around Functional Programming:
Some languages like
C or some newer functional languages don't even have a
Note that the "problem" in Object-Orientated Programming is not "objects" as as classes. The problem is "orientated".
- Like writing a class with many methods to represent a real-world idea and all the things you can do to it, rather than separating concerns and putting functions for modifying the object in a different module to the ones for representing it.
- Or when you have a method can that only be used on an instance of the object and only for that object type. When you could make a more generic function that can accept an object of various types.
Instead of modifying a object in place, you create a new one that gets modified. Then you write over the initial object.
Strings and integers are immutable in most languages (and this makes them hashable and therefore safe to use as dictionary keys). So when you you want to modify a value, you make a new one.
x = 0 x = x + 1
So for a list, we write something like:
x = [1, 2, 3] x = append(x, 4) x = sort(x) increment = (i) => i + 1 x = map(increment, x)
This makes code easier to reasonable and often shorter, because you write what you want to happen rather than how you want it to happen.
There are no
Instead, use recursion.
Or a map transformation like:
# Ruby myList.each // JS myList.map # Python map(fn, myList) [x + 1 for x in myList] # Python list comprehension
In Python at least, you get a speed benefit from using that approach, as it uses optimized C code underneath that is not reachable when using a
Functions do not have side effects that modify the state of other objects.
Well, you have to make exceptions to do something useful like interacting with a database, files on disk, an API or printing
Code becomes more reusable.
Functions are specialized and have narrower scope.
You can also chain functions together.
Code becomes easier to write unit tests for. As functions give predictable output based only on the inputs you give them.
They don't depend on data in an file or database or API and when there is no state. which is normally modified by methods in OOP like
See the Functional Programming page on Wikipedia.
See also Functional Programming on Tutorial Point.