Rust, Software Development

How to use State Design Pattern in Rust

This post is about an example implementation of the State Design Pattern in Rust.

State Design Pattern

Anything has a state. An entity has a state. Similarly, a car can be in a state of acceleration. While it is accelerating, there are some things it certainly cannot or should not do, e.g., reversing at that very moment. The State Design Pattern treats each state as a struct whose functions represent movements to the other states.  Each struct can allow or prevent some status changes. Generally, these functions run first before the actual status change that happens internally.

In technical terms, please read State Pattern.

Our Implementation

Our implementation is about a task ticket that has to be completed. Now, consider this like a JIRA ticket but only way simpler, which can it can be in any of the following states at one time: New, In Progress, or Done.

NEW means that a ticket is newly created while IN PROGRESS means that someone has started working on it. DONE means it is resolved.

Rules for Changing States

The rules of status change are simple, as depicted in the following image.Rules for Changing States using State Design Pattern

A ticket cannot go through the following status changes.

  • New tickets cannot change the status to NEW or DONE.
  • In-progress tickets cannot change status NEW or IN PROGRESS.
  • Processed tickets cannot change the status to NEW, DONE, or IN PROGRESS

Rust Codes

We have a struct JiraTicket that represents a JIRA ticket. It implements the trait Debug, State, and JiraTicketStateMovement.

Traits and State Codes

Both the JiraTicket and the “state” structs use these traits.

NEW State

IN PROGRESS State

DONE State

Usage and Demo

The codes try to change the ticket’s status from IN PROGRESS  to NEW.

Output:

What happens to our Rust State Design Pattern Example when we have a new state? With the State Design Pattern, we only need to modify JiraTicketStateMovement and the “state” structs. First, add a new function for the new state. Then, implement the function in the “state” structs in our Rust example.

Tested with Rust 1.39.0.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like