-
Notifications
You must be signed in to change notification settings - Fork 385
Create typestate.md #100
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
dgunay
wants to merge
12
commits into
rust-unofficial:main
Choose a base branch
from
dgunay:patch-1
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Create typestate.md #100
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
6ca0023
Create typestate.md
dgunay e2477de
Update typestate.md
dgunay 847fcfc
Merge branch 'master' into patch-1
simonsan 497b474
add link to typestate in SUMMARY.md
dgunay 45dc616
Add another disadvantage of the typestate pattern
dgunay df66673
Update patterns/typestate.md
simonsan f3df9ff
Update patterns/typestate.md
simonsan 639b0dd
Update patterns/typestate.md
simonsan 33be6e8
Update patterns/typestate.md
simonsan 62e2110
Update SUMMARY.md
simonsan 0d196a7
Merge branch 'master' into patch-1
simonsan 8688e48
Merge branch 'master' into patch-1
simonsan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
# The Typestate Pattern | ||
|
||
## Description | ||
|
||
|
||
The typestate pattern is an API design pattern that encodes information about an object's run-time state in its compile-time type. In particular, an API using the typestate pattern will have: | ||
|
||
* Operations on an object (such as methods or functions) that are only available when the object is in certain states, | ||
|
||
* A way of encoding these states at the type level, such that attempts to use the operations in the wrong state fail to compile, | ||
|
||
* State transition operations (methods or functions) that change the type-level state of objects in addition to, or instead of, changing run-time dynamic state, such that the operations in the previous state are no longer possible. | ||
|
||
## Example | ||
|
||
This is one example of how to implement the pattern for a simple type that needs to be initialized or otherwise prepared before use | ||
(that is, it has two states: (), and Ready). More states and operations may be added to implement a more complex state machine. | ||
|
||
|
||
```rust | ||
|
||
use std::marker::PhantomData; | ||
|
||
pub struct Ready; | ||
|
||
pub struct Thing<S = ()> { | ||
// tracks state type info at compile time, optimized out for runtime. | ||
marker: PhantomData<S> | ||
} | ||
|
||
// Private constructor to internally control what state the struct is in. | ||
fn state_constructor<S>() -> Thing<S> { | ||
Thing { marker: PhantomData } | ||
} | ||
|
||
// Operations in our default state () | ||
impl Thing { | ||
pub fn new() -> Self { | ||
Self { marker: PhantomData } | ||
} | ||
|
||
// Consumes the struct to return one with a new type state | ||
pub fn get_ready(self) -> Thing<Ready> { | ||
state_constructor::<Ready>() | ||
} | ||
} | ||
|
||
// Operations available in any state | ||
impl<S> Thing<S> { | ||
pub fn do_any_time(&self) { | ||
println!("We can do this function whenever"); | ||
} | ||
} | ||
|
||
// We can only use this function when ready | ||
pub fn do_only_when_ready(_: Thing<Ready>) { | ||
println!("We can only do this when we are Ready") | ||
} | ||
|
||
fn main() { | ||
let thing = Thing::new(); | ||
|
||
// Not ready yet | ||
thing.do_any_time(); | ||
// do_only_when_ready(thing); // this won't compile | ||
|
||
// Transition to Ready | ||
let ready = thing.get_ready(); | ||
|
||
// Now we're ready | ||
ready.do_any_time(); | ||
do_only_when_ready(ready); | ||
} | ||
``` | ||
|
||
|
||
## Motivation | ||
|
||
You are modelling a system that functions as a state machine, and want to ensure at compile-time that invalid states never occur in any runtime scenario. | ||
|
||
## Advantages | ||
|
||
|
||
* It moves certain types of errors from run-time to compile-time, giving programmers faster feedback. | ||
* It interacts nicely with IDEs, which can avoid suggesting operations that are illegal in a certain state. | ||
* It can eliminate run-time checks, making code faster/smaller. | ||
|
||
## Disadvantages | ||
|
||
* It can add some verbosity and complexity to the code. | ||
* Implementing it for complex structs can be difficult. | ||
* It can make compiler error messages very hard to understand. | ||
|
||
simonsan marked this conversation as resolved.
Show resolved
Hide resolved
|
||
## See also | ||
|
||
- [The Typestate Pattern in Rust, Cliff L. Biffle (2019)](https://web.archive.org/web/20210103081241/https://cliffle.com/blog/rust-typestate/) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.