state pattern long state class names

123 views Asked by At

I am using state pattern on 28 states in my application, the states are for membership cards that has 7 major states, there are 4 boolean attributes for the membership card that actually affects the its behavoir so i have decided to embed them with states, that's how it multiplied to 28 states.

the problem now is with states class naming, it is getting crazing, i am ending up with class state named like this Membership-UnderCreation-Printed-Linked-Premium-Frozen ----- i have hyphened different attributes to make it clear.

is it ok for state class names to be like this?! what should i do for best practice?

2

There are 2 answers

4
plalx On

Perhaps you are pushing it too far. I dont think your current approach is maintainable and depending on how all this will evolve, it could lead to an explosion of different states.

I have a few ideas on how you could tackle the problem. You could implement the 7 main states using the state pattern and use flags to track the other conditions, so within each states you could write conditionnal statements based on these. The code within functions would get slighlty more complex, however I believe it will still be more maintainable.

I do not have much information about your state transitions and everything, but another idea would be to have a single state class from which you can create anonymous subclasses by passing in a collection of conditions that needs to be met to activate the state.

Then, you do not have to name any of your states, you simply have to keep them in a collection and when any properties of the main object changes that might cause a state change, you loop over the state collection and your will find your new state by comparing the object properties with the state conditions.

Note that you could also use a HashMap to store the states and create a hash from all conditions to get a unique key. That would make state lookups faster than looping over all of them to find the next state.

3
shr On

As plalx commented, as it stands, the design is not easy to maintain. As plalx suggests, you should have only 7 main states.

For the other 4 attributes, one option is to use the decorator design pattern. Each of the 4 attributes could be designed as 4 decorator classes. Based on which attribute is set, the corresponding decorator object will wrap the original object. The decorator can then intercept calls from clients and modify the behavior based on the attribute for that decorator.