When applying the State Pattern illegal transitions should result in an exception being thrown (or at least that's what I understood from the pattern)
I know exceptions are for "unexpected behavior" where an action isn't supposed to happen. Errors would be more appropriate if the required action is common (ex: user enters a wrong password)
Now picture this, I have an admin panel where a list of orders are shown and each order has 3 buttons (Refund, Cancel, Reorder) where each one of them changes the state of the order if the operation is allowed.
The 3 buttons are enabled by default (I'm simplifying my case here as my real system is much more complex than that). Now a user can for example push the cancel button for an order with state (Cancelled) which is an invalid state transition.
- Since I expected that this illegal transition action to occur would a validation before attempting to Cancel the line be more appropriate?
- If I validate before transition do I still need exceptions in the model?
- Is there a better approach to the whole problem (ignoring disabling the buttons and client side validation)
Best Answer
Client-side measures can never solve such a problem. Even if you disable smth and/or place validation, it is still possible to send invalid requests.
In this case I would disable the
Cancel
button in the UI. When the server receives a request to change state, I would validate it at server-side, ignore the request if the state is invalid and send an error status back to client. depending on the situation, I would also show an error message likeThe order has already been canceled
.