Skip to content

Commit dc4ab22

Browse files
committed
Add advantages section comparing to the Rust Book
1 parent f7fc3fe commit dc4ab22

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

functional/stateful-types.md

+19
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,25 @@ fn main() {
231231
They would get a syntax error. The type `Interpreter<Loaded>` does not
232232
implement `set_param()`, only the type `Interpreter<Init>` does.
233233

234+
## Advantages
235+
236+
This sort of type transformation to represent state is also described in [the
237+
Rust Book](https://doc.rust-lang.org/book/ch17-03-oo-design-patterns.html#implementing-transitions-as-transformations-into-different-types),
238+
except the types are not generic. Using generic types has a key advantage: code
239+
re-use.
240+
241+
First, it allows fields that are common to multiple states to be de-duplicated.
242+
That is, if the interpreter had a common field across the `Init`, `Loaded`, and
243+
`Ready` states, making them three structs would require the field to be
244+
consistent three times. By making the non-shared fields a generic, they are
245+
implemented once.
246+
247+
Second, it makes the `impl` blocks easier to read, because they are broken down
248+
by state. Methods common to all states are typed once in one block, and methods
249+
unique to one state are in a separate block.
250+
251+
Both of these mean there is less code and it is better organized.
252+
234253
## Disadvantages
235254

236255
This is a lot of typing. Depending on the amount of change caused by state

0 commit comments

Comments
 (0)