Java – Should we validate a state transition before attempting it in the State Pattern

cdesigndesign-patternsjavaobject-oriented

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.

  1. Since I expected that this illegal transition action to occur would a validation before attempting to Cancel the line be more appropriate?
  2. If I validate before transition do I still need exceptions in the model?
  3. 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 like The order has already been canceled.

Related Topic