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.
Deependra is a Senior Developer with Microsoft technologies, currently working with Opteamix India business private solution. In My Free time, I write blogs and make technical youtube videos. Having the good understanding of Service-oriented architect, Designing microservices using domain driven design.