Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum number of states in State Pattern

I am trying to use state pattern and i have a question. Is state pattern designed only for situtations with limited number of states like this:

TCPState: 1- TCPEstablished 2- TCPLisenting 3- TCPClosed etc.

Or it can be used in cases with hundreds of states like for example an employee in an employee attendance system where an employee will have a composite state of multiple components like number of yearly vacations he has in his balance, number of hours he should compensate this month, a state to represent his hourly salary rate depending on the work load for this month, etc. each employee can have combination of multiple attributes that eventually considered to be a state with a certain behavior.

at this case there will be hundrerds of state objects, is that correct thing to do? how would you manage state objects naming? and what would you do if for example one third of the states share a certain behavior for some method, and another quarter shares another behavior for a certain method etc. i.e. not all states necisserly have a unique behavior in all it's methods. I dont think copying the implementation and pasting it into all the states that have the same behavior for this common method would be wise!

Thank you very much.

like image 597
Sisyphus Avatar asked Jan 17 '26 17:01

Sisyphus


1 Answers

There is no defined maximum number of 'State' classes, but if you implement a 'State' class for every 'state' you will likely end up with massive code duplication, which is considered a problem on its own.

Note that a 'state' as in a combination of assigned values is not the same as a 'State' class in the State Pattern, which is an implementation of a set of abstract methods. A misnomer if you ask me, a 'State' should better be called a 'Behaviour' in the pattern.

If you can capture the behaviour in a limited set of 'State' classes (i.e. if it can be built with a limited number of lines of code, so probably yes) then you can apply the State Pattern. As you already mention, you can apply the State Pattern multiple times, by maintaining more than one active states.

like image 192
The Nail Avatar answered Jan 20 '26 14:01

The Nail