You can safely pass Money objects around without having to worry about its internal state being altered unexpectedly. Money has Value Object semantics that hide its internal state behind an object literal. These are some of hoops we can jump through to ensure your state is preserved as you expect it to be, which will make your code easier to trace and debug.
However, the need to set or modify an object's properties after it's been created is very strong and occurs very frequently. What can we do?
Immutability with getters and setters
Applying functional programming to your application is not restricting all mutation, but eliminating observable changes outside of your function scope; so that executing a function leaves the system in exactly the same state as it found it. Hence, functional programs are stateless. This statement has large implications, but in the context of object creation and modification, we need to ensure that setting an object's properties does not alter it. One way of doing it is by returning new copies of the object, as so:
At first glance, this might not seem like a big deal, but fact is that the call to R.set(), which is used to modify one of the object's properties, actually copies the state of the original object and returns a brand new object olivia with the modified property, keeping the original intact. Ramda does this by first performing a deep copy of the object using R.clone.
Composition with LensesBecause Ramda's implementation of lens functions are curried, they can be easily used in compositions. As shown in the following example:
This code causes a side effect on the provided array reference, since running the function effectively changes the content of the array declared outside of its scope. If you want to avoid this inadvertent side effect, you can use lenses:
With lenses any operation on objects or arrays is immutable! This means you can be sure to pass any object wrapped in a lens into a function, and the original will never inadvertently change; thus, obeying the central principles of functional: total elimination of externally observable mutations and side effects!
For more detailed information on this topic, you can buy my book.