I am using Python and ORM, particular SQLAlchmey. I have an ORM model which implements data mapper pattern. The model has a field state, which can take one of several states, let's say NEW, CANCELLED, DONE.

I have a set of actions to perform on a model. The objective of the actions is to move the model from its current state to a target state. Examples of the actions are: cancel, complete. cancel moves the model to CANCELLED state. complete moves the model to DONE state. These actions can be performed from multiple modules of the system.

I could just assign a new state like model.state = CANCELLED, but for every action there are specific prerequisite. E.g. you cannot move the model to CANCELLED state if its current state is DONE. E.g. you cannot move the model to DONE state before a specific date.

Besides this, there are post-actions to be performed after state changes, i.e. if the model moves from DONE state, few other fields of the model to be updated.

I want to choose a design pattern that would best suit my needs. I have considered the following options:

  1. Enforce this functionality at the model level, for example in setter functions. For example when the state is being changed to CANCELLED check that the current status is not DONE. Why this does not work: There is a layer of application, which is allowed to change state to DONE from any state, or which does not require notification being send as a default behaviour.

  2. Add specific function to the model. For example method cancell(). Why this does not work: Adding them to the model would make the model too heavy. Moreover these logic is prone to change frequiently, while data representation is not, thus I would like to keep frequintly changing code separate.

I am considering the Proxy pattern. Is it a good choice or there are better alternatives.

  • What you describe here sounds like just a State Machine and there are various patterns and libraries for implementing one. However, this has nothing to do with ORM, so please find a more suitable title and double-check if your question isn't really about how to implement a state machine (in which case it's probably already answered a few dozen times and a candidate for being closed) – Frank Nov 12 '14 at 15:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.