UML – State machines

If the classes of your model define the statics, we are now left with dealing with the dynamics of the domain. With the dynamics, I mean all the “state” and “rules” that any instance object defined by a class in your model might have.

This is where UML introduces the State machine. A State machine helps us describe the different allowed states an object can be in and how it is transitioned between these states.

State machine.png

For the Car class in the model, I choose to model the State machine above.

Each box is a state. A state has a name. A state can have transitions moving into it or out of it. To follow a transition out of a state and land in another state, we must use a trigger. A trigger is a method of the class that performs all actions associated with moving from one state to another. To execute a trigger, we must first be in an action where this trigger can be used.

State machines can make the dynamics of the information in your model much more accessible. Having the rules that the state machine implies also removes the need for several other means to make sure the information does not end up in illegal states.

Car model 3.png

The current state is stored in the attribute named the state in this case. A class can have multiple state attributes (named differently) – just as objects in the real world follow different state machines depending on perspective. The perspective I have chosen above might be called LifeTimeState. And maybe there is another state attribute called CleanlinessState.

You can implement many business rules in state machines like these. Consider that your domain has a rule: “Do not start production until the deposit is paid”. I would go about it like this:

Depositpaid.png

and a Guard on the State machine:

Guard on the state machine.png

The language used to declare the guard is called OCL – Object Constraint Language. It is a language that allows you to navigate your model so you can easily make more complex rules. Consider that the Brand must be set before we start production: “self.DepositPaid and self.TheBrandOfTheCar->notEmpty”

OCL makes heavy use of your model and the rule is just as clear as your model is – using the language of the domain.

You can also define Entry and Exit actions when you enter one state and leave another.

Like this:

Production started.png

The MDriven Book - Next Chapter: Constraints

This page was edited 43 days ago on 10/02/2024. What links here