Functional Programming — Purity and Immutability

There is a series of great articles about functional programming. Purity and Immutability are two of most important concepts.

Pure functions have no side effects.

You may have heard about side effects a lot, but what exactly does that mean. Let say we have statement like y = f(x) where f is either a function or an object.

  • The f is immutable/functional/has no side-effect when, given same x, y will be same no matter what time it is
  • The f is mutable/non-functional/has side-effect when, given same x, y may be different if f’s state has changed

f’s state may change when it depends on a state which could change. The object fields and global/static variable are examples of those states. There are two ways to make it pure functions

  • remove dependencies, or
  • variables are not supported or are readonly

Functional Programming chooses to include both into its language design. That is what those great articles talk about Purity and Immutability.

So what are the benefits of doing this?

  • code is easy to understand/diagnose due to less or even no dependencies
  • code that ensures concurrency (using things like locks) is just simply not required because there is no variables or they are readonly, so code can be run in parallel without extra code

Further to the above, when a system’s components are organised in an isolated fashion (i.e. Microservices per Bounded-Context), the system is fault-tolerant (a failure in one of the components should not affect the whole system).

With code being run in parallel (which is what Functional Programming offers) and isolated components, a system is scalable and highly available. Erlang author has a great talk about this.