Patterns for Constructing Stateful Programs without Any Mutation

Edward Huang
Level Up Coding
Published in
7 min readDec 22, 2020

--

Originally published at https://edward-huang.com.

When developing an application, it is often useful to have some state in the application to detect the current point at which the program is executed. Often, we want to operate in sequential data streams, such as the parser, firewalls, communication protocol, or a stream of data. In some of these operations, the previously computed data is stored in some variable (State) and will often influence the program’s current execution decisions.

We can call these operations a stateful operation, where the program’s previous execution is carried over to the current implementation. Describing the program in terms of program state and statement in which the State will change is often used to have their programming paradigm called the Imperative programming.

Often, we can use variables to store our previous computed value to be used for current computation. However, you can also functionally write imperative style programming with State monad. If you don’t know what that is, check out my previous article on How to create a random number generator function without Side Effects.

State monad is simply a function that helps you construct a finite state machine by first describing what your program should behave. You can then insert your initial State and expect to get back the final result and the…

--

--