Note that there are some explanatory texts on larger screens.

plurals
  1. POState Pattern: How the states of an object should transition when they're involved in complex processes?
    text
    copied!<p>I have some doubts about the following implementation of the state pattern:</p> <p>I have an Order object. For simplicity, let's suppose it has a quantity, productId, price and supplier. Also, there are a set of known states in wich the order can transition:</p> <ul> <li>state a: order is new, quantity must be > 0 and must have productId. Price and supplier are not yet assigned.</li> <li>state b: someone checks the order. It can only be cancelled, or have the supplier assigned.</li> <li>state c: supplier can only fill in the price to be charged to the client.</li> <li>State d: the order is cancelled.</li> </ul> <p>1) Order.isValid() changes between states. Ie, in state a some operations cannot be done. So, they look like:<br> void setQuantity(int q) {<br> if (_state.canChangeQuantity()) this.quantity = q;<br> else throw an exception.<br> }<br> <em>Is this right, or should i get each state to implement setQuantity operation? In that case, where will be stored the value? In the order, or the state? In the latter case, i will have to copy the data in each state transition?</em></p> <p>2) orderProcessor.process(order) is an object that checks order.IsValid, transition the order to some state, saves it to the db and perform some custom actions (in some states, admin is notified, in others the client, etc). I have one for each state.<br> In StateAOrderProcessor, the person that checks the order is notified via email, and the order is transitioned to state b.<br> <em>Now, this pushes the state transitions outside the Order class. That means that Order has a 'setState' method, so each processor can change it. This thing to change the state from the outside does not sounds nice. Is thas right?</em></p> <p>3) Ahother option is to move all the validation logic to each state's processor, but now i have to track when a order's quantity was changed to see if that operation is valid in the current state. <em>That leaves the order kind of anemic to me.</em></p> <p>What do you think guys? Can you give me some advice to desing this thing better?</p> <p>Thank you very much.</p> <p>Nick</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload