3

I'm about to implement my first State Machine and I'm left with one question, which is the acceptable coding form on who should change the state of the object/entity? Should the StateMachine change the state? Should the object itself change its own state? Should a sevice (e.g. IncidentTicketService) change the state of the entity (IncidentTicket) ?

Concrete example

public enum IncidentState {
    OPEN, CLOSED, CANCELLED, PENDING
}

...

public class IncidentTicket {
   private String state;
}

...

public IncidentTicketStateMachine {
   // code here depends if this object is doing the state change, or 
   // just indicating which are the next/previous states based on the 
   // provided object in a constructor... I guess.
}

...

# only if this is common practice to change the state of the object
public class IncidentService {

   private IncidentTicket incidentTicket;

   public IncidentService(IncidentTicket incidentTicket) {
      this.incidentTicket = incidentTicket;
   }

   public void nextState() {
      this.incidentTicket.setStatus(....);
}

...

I don't mind coding it either way (object changes state vs state machine), I'm asking since I want to find out which of the two is most common?

Thanks

1 Answer 1

4

This seems self-evident to me. While the Object Entity is responsible for storing the state, the State Machine itself is responsible for managing the state.

It's not about "what is the most common," though. Popularity is seldom a good way to make decisions. It's about doing the thing that best solves your specific problem.

By way of example, imagine drawing money out of a checking account using an ATM. You would never expect your wallet to know how much money it contains, nor would you expect the money to draw itself out of your account.

That said, nothing prevents you from attaching some helper logic to your entity. But ultimately I think the responsibility for maintaining and interpreting the state lies with the State Engine, not with the entity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.