Functional Programming Part 3 – Immutability
One rule of Functional Programming is immutability; this means that data of any kind can’t be changed. Now, hold on before you throw Functional Programming out the window, let’s remedy your concern; you can still operate on objects. Confused? Let’s learn about immutability and how to leverage it to create better applications.
Immutability means the objects don’t change their internal state; your complex object will always have the same values. That might sound bad, but it’s actually awesome! Here’s why: less mutable states means less complexity. Objects in object-oriented programs are complex and often change the internal state of the objects within the program. Now, imagine the tight coupling and constant passing of objects in your program. The complexity and the working parts will start to overwhelm you quickly. Secondly, if one part of the system changes the object in a way the system isn’t expecting — errors will haunt you. Immutability solves this problem by managing complexity.
Solving Complexity With Immutability
We can solve complexity by making a copy of the original object. This is an important concept because we can modify the copy without worrying about the internal state of the original object. Once our modifications are complete, we can replace the original with the copy. A lot of problems slowly begins to disappear, but one primary factor needs to be addressed: the object creation overhead.
Object Creation Overhead
In a raw environment, working with immutable objects can lead to significant issues if not managed properly. Understanding garbage collection (removal of unused variables and objects) is key. This is because your object creation will go up due to creating copies, lowering performance. In your best internet, it’s better to use it sparingly when you need it.
It may seem great to fully embrace a single style, but keep what you’ve learned in your back pocket. Every pattern and principle are there to make your life easier. If you think combining objects with your functional programming approach works — do it. Immutability is about lowering the number of states changes; using that principle effectively will lead to better code.