Functional programming : Avoid Shared state

Rahul Lohakare
3 min readFeb 19, 2022

--

Sharing is not always bad though…

What is a shared state?

Shared state is a variable, object, property of an object or memory space that can be accessed from more than one function.

What’s the problem with shared state ?

Accidentally changing the value of a variable which is shared in the entire code base may lead to potential and complex bugs. Such bugs are hard to debug and solve.

See the below example

Accidental shared state update

Yes It’s easy but it’s costly

I know it is easy to write a shared state and read/write it from anywhere in the app.

For very small things it is ok but, imagine having 1000 files and functions having a shared state and no idea which file or function is changing the state, intentionally or accidentally. In this case If the code base increases bugs due to shared state increases.

Mutable shared state and Immutable shared state

For an shared Immutable state it is harmless as nobody will be able to directly change it. Example of it is React state management.

For a mutable shared state, we have to keep track of the history or changes done on it. Also a locking mechanism will also be needed. Which is expensive.

Even if the sequence of calling functions got changed, output will change.

How to fix problem of mutable shared state ?

Avoid shared state and while writing code, write logic such that there will be no shared state. Still needed a shared state ?

Use any one of the below methods

A) Copy while using it.

B) Copy at the source.

Prevent accidental changes and not intentional

The primary focus of “Avoiding shared state” is to prevent accidental updates of mutable variables. But, you might be thinking, what if we actually need to change the value of a mutable variable? Like if we have a configuration variable or property in a window object that has an effect on the entire app.

Sure, We can change it intentionally. But the recommended way for it is having a function (setter). Benefits of having a setter function is you can log or track the direct changes to mutable state variables.

State in react

Many of you are might be confused like me. That we normally use state in react. That is something shared too, then why react allowed shared state.

The reason is react never allows shared state. The state which we use in react is an Immutable state by its own way. You cannot directly change state in react. To change any state you have to call setState function or use callback function in case of hook. That is where react added Immutability. Those functions internally never change the value of state directly.

Congratulations ! you’ve just learnt a new concept of functional programming.

--

--

Rahul Lohakare
Rahul Lohakare

Written by Rahul Lohakare

I am Senior Software Engineer with almost 8 years of experience. I love working with technologies like React, Angular, Javascript, CSS and HTML.

No responses yet