Could it be a good alternative for state pattern?

Viewed 18

I am trying to design in DDD a common orders and order lines aggregate.

The orders can be in some states, and each state allows to do some actions. So I think that the state pattern it is a good option.

I don't enter in deep details about the state pattern, there is a lot of documentation, but If I am not wrong, this pattern needs to create class for each possible state and implement the interface with the actions that can be perform. This make to have to modify the code in the following cases:

1.- if I want to add a new state.

2.- if I want to modify the actions that a state allows to do.

3.- if I want to add new actions that can be perform.

So I was thinking in another option, to have only one class for the state with properties that tells which actions can be performed. Something linke that:

class State
{
    long Id,
    bool CanDoAction1;
    bool CanDoAction2;
    ....
}

Then, in the database, I would have a table for the states:

States(Id, StateName, CanDoAction1, CanDoAction2...)

And I would have all the states:

State1: (1, 'Create', true, false); //1 for true and 0 for false in the case of Sql Server, for example
State2(2, 'Accepted', true, true)

...

For me the adavantege of this is:

1.- I can modify without modifying code what actions a state can do. Just updating the database. 2.- If I need to add a new state, I can do it without modifying the code, just add the new state and telling which actions can do.

Disadvantages:

1.- If an order can do a new action, I have to add the new field to the database and modify the code. In state pattern I would only need to modify the code.

2.- In some way, we could considerate that the logic of the domain is outside the domain, because I set what is allowed and what no, in the database, but from another point of view, really the domain get the information from the database and decide what to do according the information, so at the end is the domain who decides. It is true that with the state pattern all is hardcode, so it is not possible no modify the behavior.

So my doubt is, does it would be an option thinking in DDD or it is better to use the state pattern although it implies to modify code in each the requirements are changed?

Thanks.

0 Answers
Related