State design patterns, when to use, pros and cons

The state design scheme is used to model changes in the state or state of an object by delegating the rules for such changes to individual objects representing each possible state.

When we should use the state model?

The state model is a good candidate to apply when you have an object with a relatively complex set of possible states, with many different business rules on how state transitions occur and what should happen when the state changes.

If the object is merely a state-owned property, at any time, any state can be updated with at least special logic, the State Schema increases needless complication. However, for the objects representing the real world concepts, with a compound workflow, the state structure can be a decent option.

What are the Advantages of using this model?

The state model minimizes conditional complexity, eliminating the need for if and switch statements on objects that have different behavioral requirements that are unique to different state transitions. If you can represent the state of the object using a finite state machine diagram, it is easy enough to convert the diagram into the types and methods of the state design model.

What are the Disadvantages of using this model?

The state schema requires a large amount of code to be written. Depending on the number of different defined state transition methods and how many possible states an object can have, you can quickly write dozens or more different methods. For N states with M transition methods, the total number of methods required will be (N + 1) * M. In the previous example for an insurance policy, there are 5 different states, each of which must define 5 methods (ignoring for the moment the ListValidOperations method), for a total of 25 methods in the state types. Thus, the type of policy context must also define the 5 methods of state transition, for a total of 30 methods to be written.


About The Author

Deependra Kushwah
Deependra kushwah is a member of the fastest growing bloggers community "betechnical", Author, Youtuber, and hardcore Coder. I love writing code in different languages, I also write blogs on tech tutorials, gadgets review and also post some technical videos on youtube on many topics.

This site uses Akismet to reduce spam. Learn how your comment data is processed.