Lecture 8: Type-based Modelling and Design
This lecture discusses the concept of type-based modelling and design,
and how it can be used to improve the quality of systems programs. It
discusses the idea of type-driven development for structuring systems,
and how this helps model the problem domain and help validate the
design. And it discusses some specific examples of this, using types
to model numeric values; using enumerations for alternative, options,
and results; and in the modelling of state machines.
Part 1: Type-based Modelling and Design
The first part of the lecture introduces the idea of type-driven
development, a way of developing software that starts by defining
the types then using those to guide the development of the code
and functions necessary to complete the system. It outlines why
this approach is appropriate for building robust, reliable, systems
programs in languages with powerful type systems, such as Rust.
00:00:00.266
The previous lectures, and the lab exercises,
00:00:02.833
have began to introduce you to Rust,
00:00:05.200
a modern strongly typed systems programming language.
00:00:08.633
In this lecture, I want to move
00:00:10.833
on and talk about type based modelling
00:00:12.566
and design. That is, the act of
00:00:14.366
using the type system to help with
00:00:16.266
structuring, and arranging, the design of a program.
00:00:20.933
In this first part, I want to
00:00:22.833
talk about type-driven development.
00:00:25.600
Modern programming languages such as Rust,
00:00:28.433
which we’re using in this course,
00:00:30.266
Swift, OCaml, Scala, F#, and so on,
00:00:34.066
have very expressive type systems, and it's
00:00:37.166
possible to use the type system to
00:00:38.700
help ensure the correctness of the code that you write.
00:00:42.300
One way of doing this is an
00:00:44.133
approach known as type driven development,
00:00:46.600
which was pioneered in a language known as Idris.
00:00:49.966
The book shown on the right hand
00:00:51.700
side of the slide is is the
00:00:53.400
Idris book, which gives an introduction to that language.
00:00:56.933
In a type driven development approach,
00:00:59.666
rather than structuring a program initially around
00:01:02.433
the control for flow, around what program should do,
00:01:05.533
you structure it first around the types.
00:01:08.666
Think about what sorts of data,
00:01:10.233
what sort of objects, your program should
00:01:11.933
be working with, and write down the
00:01:13.666
types that describe those objects.
00:01:15.966
Then using the types as a guide,
00:01:18.400
write down the functions. Write the input
00:01:21.100
and output types of those functions,
00:01:23.100
validate that the design type checks and
00:01:25.533
is consistent, and then gradually refine the functions.
00:01:30.533
The fundamental approach is that rather than
00:01:32.333
thinking of the types as a way
00:01:34.100
of checking the code, you think of
00:01:35.933
them as a plan, or as a
00:01:37.166
model, for the solution. And you build
00:01:39.400
up the the design around the types,
00:01:41.666
and then fill in the details of
00:01:43.533
how the operations are performed.
00:01:45.966
You let the types, and the compiler,
00:01:48.166
guide the structure of your design.
00:01:51.733
The first stage is to define the
00:01:54.433
types. That is, think of the types
00:01:57.133
which are needed to build a model
00:01:58.600
of the problem domain.
00:02:00.266
Think about who's interacting, what are they
00:02:02.533
interacting with, and what sorts of things
00:02:04.266
do they exchange.
00:02:05.700
This will likely lead you to define
00:02:07.733
types such as senders and receivers.
00:02:10.133
You may have types that represent the
00:02:11.833
connections between different entities in the system,
00:02:14.233
or the TCP segments being transmitted over
00:02:16.933
those connections. Or, if you're building another
00:02:19.866
type of application, you may have employees,
00:02:22.133
vehicles, or different types of cargo that
00:02:24.733
are transported in those vehicles.
00:02:28.066
Think about what sort of properties describe
00:02:30.766
those people and those things. And think
00:02:33.266
about what sort of data is associated
00:02:35.766
with each of them.
00:02:37.700
This probably leads you to types such
00:02:40.133
as email addresses, names, manufacturers. Or types
00:02:43.833
representing properties of objects, such as a
00:02:45.933
temperature, or a sequence numbers, or a colour.
00:02:49.566
Think about the types of states that
00:02:51.966
the system can be in, and the
00:02:53.600
types of states the different interactions can
00:02:55.633
be in. A messaging app, or an
00:02:58.033
email client, for example, may have states
00:03:00.333
that represent the progress of sending a message.
00:03:04.300
It may have a state to indicate
00:03:06.000
that it is connecting to the server,
00:03:07.666
that once it is connected that some
00:03:09.966
sort of authentication is required or
00:03:11.966
whether it’s logged in. It may have
00:03:13.966
states to represent whether the message has
00:03:15.700
been sent, or is in the process of sending
00:03:18.633
Initially, the types might very well be
00:03:21.100
ill-defined and abstract. That doesn't matter.
00:03:23.766
Write them down anyway. Refine them later.
00:03:26.566
Circle around,
00:03:27.600
rebuild and redevelop the types as you
00:03:29.533
get a better understanding of the problem.
00:03:31.866
The main thing, though, is to think
00:03:33.400
about what types you need to model
00:03:35.200
the problem domain.
00:03:36.500
And think less about the structure of
00:03:38.200
the code, and more about the structure
00:03:39.900
of the problem space, and representing that
00:03:41.833
as a set of types.
00:03:44.966
Once you've done that, think about the
00:03:47.233
properties that are associated with those types.
00:03:50.633
Think about the types of data
00:03:52.700
which are associated with each of the
00:03:54.366
things in your system, and what properties
00:03:56.233
do those things have.
00:03:58.133
For example, a program dealing with customer
00:04:00.633
information for a shipping company might have
00:04:03.233
a sender objects that hold the name
00:04:06.333
of the customer, their email address,
00:04:08.300
and their postal address.
00:04:10.766
It's easy to write down such a
00:04:12.366
type, as we see on the slide.
00:04:14.466
We don't need to worry about how
00:04:16.066
a name is formatted, or an email
00:04:17.900
addresses is formatted, or a postal address
00:04:19.766
is formatted. We just note that there
00:04:21.600
is a type for that, and define
00:04:23.400
it later when we need
00:04:24.966
to understand the details.
00:04:28.433
Similarly, we think about states the various
00:04:31.233
objects are in, and we write down
00:04:33.833
types to represent the states.
00:04:36.500
For example, if the system is logging-in
00:04:38.800
to some some networked resource, it may
00:04:41.533
have states representing a system which has
00:04:44.000
not started connecting, and is not connected at all;
00:04:47.166
a system which is in the process
00:04:49.366
of connecting to remote server; and a
00:04:51.900
system which has connected, but has not
00:04:53.900
yet authenticated; and a system which is
00:04:55.766
authenticated and logged in.
00:04:57.866
And, as we see in the enum
00:05:00.133
State example, it’s easy to write down
00:05:02.600
a type that represents those different aspects
00:05:04.900
of the system behaviour.
00:05:06.800
It may also make sense to represent
00:05:08.900
the different aspects of the behaviour,
00:05:10.866
the different states the system is in,
00:05:12.633
in different data types.
00:05:14.866
For example, we can model authenticated and
00:05:17.600
unauthenticated connections as two
00:05:20.066
different types of objects, both of
00:05:22.033
which hold the underlying TCP socket that
00:05:24.233
represents the connection to the remote resource.
00:05:26.866
But which are stored in different types
00:05:28.600
of structs, depending on what the system
00:05:31.066
is doing at the time.
00:05:33.166
The important thing is to write down
00:05:34.900
the types, which you can then refine
00:05:37.066
and extend as needed, as we get
00:05:38.700
a better handle on how the system is working.
00:05:43.166
Once we’ve started by writing down the
00:05:45.533
types, we then move on to sketching out functions.
00:05:49.533
The idea here is that by using
00:05:51.300
the types as a guide, we sketch
00:05:53.200
out the function prototypes and leave the
00:05:55.333
concrete implementation of the system until later.
00:05:58.900
The example on the slide shows how
00:06:01.700
one might sketch out the design for
00:06:03.500
an email client, for example.
00:06:05.833
An email client that has connected to
00:06:07.833
the server can be one of two states.
00:06:10.800
Initially after it’s established the connection,
00:06:13.266
it will be in an unauthenticated state,
00:06:16.000
where it's connected to the server that
00:06:17.800
has not yet logged in.
00:06:19.466
In this state, which we represent by
00:06:21.633
the unauthenticated connection at the bottom of
00:06:23.533
the slide, the only possible actions that
00:06:25.800
can perform are to login or to disconnect.
00:06:29.633
If it logs in, it needs to
00:06:31.566
provide some credentials to the server.
00:06:33.833
And, as a result of that,
00:06:35.300
it will either successfully login, returning an
00:06:37.966
authenticated connection,
00:06:39.633
or it will have provided the wrong
00:06:42.400
credentials, and we'll get a login error
00:06:45.100
of some sort.
00:06:46.433
The important thing here is that this
00:06:48.933
behaviour is reflected in the types and
00:06:51.366
the operation of the function.
00:06:53.333
We have an authenticated connection, and we
00:06:55.900
perform a login operation on that connection,
00:06:57.833
giving it some credentials.
00:06:59.533
If it succeeds, it returns
00:07:01.566
an authenticated connection, a different connection type.
00:07:05.700
Once we have an authenticated connection,
00:07:07.866
we can perform the other types of
00:07:09.400
operations you may wish to perform in
00:07:11.066
an email client. You can list the
00:07:13.066
folders, you can list the messages in
00:07:15.033
a folder, and eventually you can disconnect.
00:07:18.733
What's important here is that the behaviour
00:07:21.066
of the system is obvious just from
00:07:23.133
looking at the function prototypes. And the
00:07:25.800
different types of object we’re dealing with
00:07:27.800
constrain the possible behaviours.
00:07:30.100
If we're not logged in the only
00:07:32.133
things we can do, given that we
00:07:33.766
have an unauthenticated connection, is login or
00:07:35.900
disconnect. if we are logged in,
00:07:38.933
the only things we can do is
00:07:40.833
list the folders, list the messages, or disconnect.
00:07:44.700
It's perhaps obvious, but we can't try
00:07:47.366
to list the folders before we've logged
00:07:49.066
in, and we can't try to lock
00:07:50.833
it login twice. And it's not the
00:07:52.966
system prohibits us from doing this at
00:07:54.666
runtime, is that the code won’t compile
00:07:57.066
if we try to perform the operations in the wrong state.
00:08:00.333
Those functions, those operations, don't exist on
00:08:03.366
the types representing the other states of the system.
00:08:08.266
And this is one of the key
00:08:09.566
points of Type Driven Design. The behaviour
00:08:12.566
should be obvious from the types,
00:08:14.133
and the types should constrain the behaviour.
00:08:17.700
In the simplest case. This means using
00:08:20.000
specific types that model the problem domain,
00:08:22.600
rather than using generic types.
00:08:25.233
That is, pass a username parameter around,
00:08:28.033
rather than a string. Or pass a
00:08:30.333
temperature in Celsius type around, rather than an integer.
00:08:33.666
By using the more specific types,
00:08:35.966
the compiler can check what we're doing.
00:08:38.500
It can check that the behaviours we're
00:08:40.666
doing makes sense, and can check our
00:08:42.366
design. Essentially it's machine checkable documentation.
00:08:46.133
If we structure the code wrong,
00:08:47.766
it just won't compile.
00:08:50.466
Similarly, as we saw on the previous
00:08:52.666
slide, encode the states as the types,
00:08:55.466
and the state transitions as functions that
00:08:57.800
manipulate those types.
00:08:59.566
The diagram shows an example state machine
00:09:01.600
for an email client.
00:09:03.933
You start with a pre-connection, where the
00:09:05.900
system is not yet connected to the server.
00:09:08.400
You connect, and that consumes the
00:09:10.433
pre-connection and returns a new type representing
00:09:12.866
an unauthenticated connection.
00:09:15.133
Given an unauthenticated connection, you can either
00:09:18.200
disconnect, which closes down the connection and
00:09:20.433
gives you back a pre-connection,
00:09:22.433
or you can attempt to login.
00:09:24.166
And if that's successful you'll get an authenticated
00:09:26.700
connection object.
00:09:28.166
Given an authenticated connection
00:09:30.066
object, you can list folders, send and
00:09:33.233
receive email messages, are you can disconnect.
00:09:36.700
We see that the types represent the state machine,
00:09:39.533
and that the functions which transition between
00:09:42.400
the different states return different types.
00:09:46.366
The login function, for example, consumes enough
00:09:49.633
an unauthenticated connection objects and returns an
00:09:53.000
authenticated connection object.
00:09:55.200
It forcibly moves the program from the
00:09:57.933
unauthenticated state to the authenticated state,
00:10:00.766
because it takes away that object and
00:10:02.633
returns the new object.
00:10:04.633
And the functions only get implemented on
00:10:06.800
the types where they make sense to
00:10:08.366
enforce the behaviour, enforce the logic,
00:10:10.866
enforce the state machine of the system.
00:10:14.566
Again, the goal is that the types
00:10:17.033
and the functions provide a model of
00:10:19.033
the system. They define what you're working
00:10:21.600
with, and how the system moves between
00:10:24.066
its various states as the different operations are performed
00:10:27.733
You sketch out an initial design,
00:10:29.766
and then you iterate as you go.
00:10:31.933
Each time just filling in enough details
00:10:34.266
to keep the system compiling, and using
00:10:36.533
the compiler to check for consistency.
00:10:39.266
And you gradually refine the design,
00:10:41.566
you refine the types, you refine the
00:10:43.266
functions, you gradually fill out the function
00:10:45.266
bodies, until the whole system has been
00:10:47.766
modelled. And, gradually, add in the concrete
00:10:50.100
implementation details, refining as needed.
00:10:53.366
Essentially, what you're doing is working with
00:10:55.400
the compiler to validate the design,
00:10:57.466
before you write the detailed implementation.
00:11:00.300
Then, as you gradually fill in the
00:11:01.966
details of the implementation, the compiler keeps
00:11:04.600
you right. It validates your design for
00:11:06.766
correctness at all points through the operation
00:11:08.700
of the system.
00:11:11.366
It's an approach which is known as
00:11:13.233
correct by construction.
00:11:15.466
Use the types, use the type system,
00:11:18.300
to model and check the problem space
00:11:20.833
and check your design. And to debug
00:11:23.500
your design before you even begin to
00:11:25.333
run the code.
00:11:27.466
The idea is that nonsensical operations in
00:11:30.100
your program don't cause the system to
00:11:31.833
crash, rather they just don't compile.
00:11:35.566
It's a change in perspective in the
00:11:37.600
way we write code.
00:11:39.566
Use the type system, use the compiler,
00:11:43.000
as a model checking tool to help validate your design.
00:11:47.033
Debugging should be a process of checking
00:11:49.200
the design for correctness,
00:11:51.200
not finding where the segmentation fault was.
00:11:56.366
So that concludes this part of the lecture.
00:11:59.366
I've tried to introduce the idea of type-driven design.
00:12:03.133
When building a system in the type
00:12:04.800
driven design approach, start by thinking about
00:12:07.466
the types, rather than the control flow.
00:12:09.833
Write down the types describing the system,
00:12:12.933
modelling the problem domain. Sketch out the
00:12:16.033
function prototypes, show how they transition between
00:12:19.666
the types, and gradually refine and add
00:12:22.133
detail as needed until you end up
00:12:23.966
with a working system.
00:12:25.766
Use the compiler and the type system to debug your design.
00:12:30.266
In the next part of this lecture, I’ll move on
00:12:32.800
to talk about some design patterns,
00:12:34.300
and show how this can be done in practice.
Part 2: Design Patterns
Part two of the lecture expands on the ideas of type-driven development,
and discuss some specific design patterns. In particular, the lecture
discusses the use of specific rather than generic types for numeric
values; and the use of enumeration types, such as Option and
Result; to being to express features of the problem domain in
the code. This helps model the problem, and lets the compiler start to
help check system designs for consistency and correctness.
00:00:00.266
In this second part,
00:00:01.900
I want to talk about some design patterns
00:00:04.066
that can help enable type-driven design.
00:00:06.533
In particular, I want to talk about
00:00:08.500
the use of specific numeric types to
00:00:10.966
replace generic and integer and floating point types,
00:00:13.700
and about the use of enumerations to represent alternatives.
00:00:18.466
One of the key questions to ask
00:00:20.500
when building a system, according to the
00:00:22.466
type driven design approach, is whether a
00:00:24.933
numeric value is really best represented as
00:00:27.233
a floating point value or an integer,
00:00:29.533
or does it have some meaning that
00:00:31.300
could be included in the types.
00:00:33.600
For example, is the value actually a
00:00:35.733
temperature in degrees Celsius or degrees Fahrenheit,
00:00:39.100
a speed in miles per hour or
00:00:41.233
kilometres per hour, a user ID,
00:00:43.833
a packet sequence number, or whatever.
00:00:47.066
The idea is that it should be
00:00:48.566
possible to encode the meaning of a
00:00:50.133
numeric value in its type, so the
00:00:52.100
compiler can check for consistent usage of that type.
00:00:56.133
Operations that mix different types should fail
00:00:59.000
if the types don't match. Or they
00:01:01.200
should perform safe unit conversions.
00:01:04.766
And operations that are inappropriate for a
00:01:07.166
type shouldn't be possible.
00:01:10.000
That the news article shown on the
00:01:12.000
slide gives a famous example of the
00:01:13.700
problems this sort of confusion can cause.
00:01:16.866
The software for the Mars Climate Orbiter
00:01:19.066
used metric units in some parts of
00:01:20.866
the code, and Imperial units in others,
00:01:23.400
and wasn't able to tell when the two were being mixed up.
00:01:27.200
The result was that the spacecraft crashed
00:01:29.633
into the planet, rather than entering orbit,
00:01:32.266
wasting many hundreds of millions of dollars
00:01:34.633
and many years of work, because it
00:01:36.766
fired its thrusters for too long,
00:01:38.300
due to a miscalculation.
00:01:40.966
I'd argue that this type of error
00:01:42.900
shouldn't be possible. Well written code should
00:01:46.066
encode the units into the numeric types.
00:01:49.066
If your program is mixing up Pound
00:01:51.066
Force Seconds and Newton Seconds, as happened
00:01:53.700
in the Mars Climate Orbiter, the code
00:01:56.333
shouldn’t fail at runtime – it shouldn’t compile.
00:02:00.066
The goal then,
00:02:01.200
should be to represent the different units,
00:02:03.100
the different types of numeric values,
00:02:05.166
in the type system.
00:02:08.733
So let's make this a little bit more concrete.
00:02:12.700
The code on the right is a very simple example.
00:02:15.966
It sets the variable C to be
00:02:18.066
15 – the temperature in degrees Celsius,
00:02:20.966
And the variable F to be 50
00:02:23.000
– a temperature in degrees Fahrenheit.
00:02:25.266
And it then calculates the value T
00:02:27.366
as being the sum of F and
00:02:28.900
C, and prints out the result.
00:02:31.566
It prints out the value of 65.
00:02:33.800
The sum of 50 and 15.
00:02:36.233
And, numerically, this makes sense. However,
00:02:39.700
as a programmer, we know that it's
00:02:41.466
actually giving the wrong answer. Unfortunately,
00:02:44.233
the compiler doesn’t.
00:02:46.566
The compiler doesn't know that 15 Celsius
00:02:49.233
plus 50 Fahrenheit is 109 Fahrenheit,
00:02:52.033
so it silently gives the wrong answer.
00:02:55.033
The constraints the programmer knows about the
00:02:56.966
design are not represented in the types,
00:02:59.933
so the compiler can't catch the mistake.
00:03:04.466
To begin to address this problem,
00:03:06.266
we should define more specific types representing
00:03:08.833
temperatures in Celsius and in Fahrenheit,
00:03:11.500
and use those types, instead of integers
00:03:13.766
or floating point values throughout our program.
00:03:19.000
For example, if we look at the
00:03:20.600
main function at the bottom of the
00:03:22.300
sample on the slide, we let the
00:03:24.366
value C equal 15 Celsius and the
00:03:26.666
value F equals 50 Fahrenheit, and then
00:03:30.000
when we try to add them,
00:03:31.366
you get the error you see on
00:03:32.600
the left of the side. The code doesn't compile.
00:03:36.866
It's expecting Celsius. It found Fahrenheit.
00:03:39.866
And t here's no conversion between them
00:03:41.633
defined. The compiler detects the bug.
00:03:46.200
How do we define these more specific types?
00:03:50.633
They’re tuple structs, as shown at the top of the listing.
00:03:54.866
They derive the PartialEq and PartialOrd traits,
00:03:57.833
from the standard library, that allow them
00:04:00.633
to be compared for equality and provide
00:04:02.866
ordering. And they derive the Debug trait,
00:04:05.900
that allows them to be printed by debugging functions.
00:04:09.700
And, we see in the rest of
00:04:11.300
the code, we implement the addition function,
00:04:13.466
the Add trait from the standard library,
00:04:15.766
that allows us to add values in
00:04:17.566
Celsius together, or allows us to add
00:04:19.833
values in Fahrenheit together.
00:04:22.566
So if we have the types right,
00:04:24.366
if we're consistently using Celsius, or if
00:04:26.633
we're consistently using Fahrenheit, the addition will
00:04:29.333
work correctly.
00:04:31.433
However, in this case the code isn't
00:04:33.266
correct and the compiler catches our mistake.
00:04:37.433
Now this is obviously a simple example.
00:04:40.600
We’re only defining Celsius and Fahrenheit types,
00:04:43.166
and we only implement the addition operation,
00:04:45.733
and we only derive the partial equality
00:04:48.433
and partial ordering traits.
00:04:50.233
And of course in a real implementation
00:04:52.666
we’d also implement subtraction and multiplication and
00:04:55.500
division, and possibly a number of other operations.
00:04:59.366
But it shows the principle.
00:05:02.133
We can begin to catch errors by
00:05:04.300
using specific numeric types in place of the generic types.
00:05:09.033
There's some complexity here, of course.
00:05:11.566
We need to define tuple structs to
00:05:13.400
represent the Celsius and Fahrenheit types,
00:05:16.233
and we need to implement the various
00:05:17.700
traits for the operations we require.
00:05:20.866
There's more up-front design work, more up-front
00:05:24.233
implementation work, but we gain the ability
00:05:27.366
to check the designs for correctness.
00:05:31.000
For small programs this probably isn't a
00:05:32.866
win, but as the system gets more
00:05:35.333
complex, and as we include more information
00:05:37.766
about the constraints on the design in
00:05:40.200
types, we can catch more and more
00:05:41.733
bugs. It's very much a win overall for large systems.
00:05:49.066
The type system in Rust is flexible
00:05:51.100
enough that we can add more features
00:05:53.333
to make use of these types more
00:05:54.833
natural. For example, we can add implementations
00:05:58.200
that perform unit conversions.
00:06:01.300
The standard library defines traits to represent
00:06:03.900
standard numerical operations, such as addition,
00:06:06.766
subtraction, multiplication and division, for example,
00:06:10.433
that are parameterised by the types on which they operate.
00:06:14.500
In this example, we implement the Add
00:06:16.866
trait, with Fahrenheit as a type parameter,
00:06:19.666
for the Celsius type. This describes how
00:06:23.033
you add a Fahrenheit value to a Celsius value.
00:06:26.166
And it allows the code in the
00:06:28.100
main() function to successfully add Celsius and
00:06:30.666
Fahrenheit values and print out the correct result.
00:06:36.433
You should also think whether all the
00:06:38.500
standard operations makes sense for the numeric
00:06:40.533
types you define.
00:06:43.500
It's reasonable to compare temperature values for
00:06:45.733
equality, for example, or to compare two
00:06:48.333
temperatures to see which is the largest,
00:06:50.700
so you'd implement the standard equality and
00:06:52.933
ordinal traits that provide these operations.
00:06:56.866
It doesn't necessarily make sense to implement
00:06:59.300
such operations for all types, though.
00:07:01.500
If you have a UserID type,
00:07:03.700
you may want to implement the equality
00:07:05.633
trait to be able to check if
00:07:06.866
two UserID values are the same.
00:07:09.833
But adding two UserID values together,
00:07:12.633
or comparing UserID values to see which
00:07:15.466
is largest, may not be meaningful.
00:07:18.766
You don't necessarily need to implement all
00:07:21.133
the standard operations for the specific numeric
00:07:23.266
types you define. You just implement those
00:07:25.566
that makes sense for those types.
00:07:28.533
Not all numeric types are actually numbers,
00:07:30.933
and not all numeric types should be
00:07:32.733
treated as if they are numbers.
00:07:34.966
Some are merely identifiers, and you can
00:07:37.266
make sure that they're used in that way,
00:07:39.033
by disallowing operations
00:07:40.433
that are not meaningful for the data.
00:07:45.300
What's interesting is that wrapping numeric values
00:07:48.233
inside tuple structs in this way
00:07:50.133
has no runtime overhead in Rust.
00:07:53.333
There's clearly some programmer overhead.
00:07:56.300
The programmer needs to think about what
00:07:58.900
types exist, and what operations make sense
00:08:01.066
on those types. And needs to implement
00:08:03.733
the standard operations. So there's a bunch
00:08:06.266
of extra code that's needed. There’s more
00:08:08.666
up-front design work, more up-front implementation work.
00:08:12.633
And I don't want to downplay this.
00:08:14.300
It can be quite a lot of
00:08:15.366
work. You need to be implementing a
00:08:17.733
reasonably large system before it becomes worth the effort.
00:08:22.166
I’ll note, though, that there are macros,
00:08:24.500
such as the newtype_derive crate mentioned on
00:08:26.833
the slide, that make this easier in
00:08:28.666
the common cases, and make it straightforward
00:08:31.300
to define the common operations with little code.
00:08:36.500
This extra code – this extra implementation
00:08:39.266
effort – leads to no runtime change
00:08:41.400
in the generated code. The additional checking,
00:08:44.966
the additional functionality, exists purely at compile time.
00:08:50.166
Why is there no runtime cost?
00:08:53.466
Well, in part because tuple structs add
00:08:56.100
no extra information compared to an integer,
00:08:58.700
or a floating point type. They hold
00:09:01.366
the same values, and so have the
00:09:03.533
same size. And since Rust doesn't automatically
00:09:06.700
box values, they’re passed around in exactly
00:09:08.966
the same way as the primitive types.
00:09:12.400
When generating code, the compiler and optimiser
00:09:15.400
recognise that the operations being performed are
00:09:17.966
equivalent to those on the primitive types,
00:09:20.566
and will generate the exact same code
00:09:22.600
to do so, as if they were
00:09:24.266
operating natively on those primitive types.
00:09:27.500
When adding Celsius and Fahrenheit values,
00:09:29.833
for example, as we saw in the
00:09:31.766
previous slides, the code that’s generated is
00:09:34.400
the exact same code as if we
00:09:36.466
were natively working with floating point values.
00:09:41.000
Wrapping the primitive type in a tuple
00:09:43.533
struct and implementing the various operations provides
00:09:46.666
compile-time checking for correctness, but doesn’t affect
00:09:49.466
the generated code in any way.
00:09:52.633
And this behaviour is not unique to
00:09:54.433
Rust. Equivalent C++ code has exactly the
00:09:58.400
same properties, for example, but there are
00:10:01.233
not many languages which allow you to
00:10:02.833
pass unboxed values around, and to have
00:10:05.400
precise control over the data layout.
00:10:08.833
The type system in Scala is expressive
00:10:11.366
enough to represent numeric types such as
00:10:13.033
these, and to perform the sorts of
00:10:15.233
checks I’ve described. But, because the resulting
00:10:18.666
code runs on the Java virtual machine,
00:10:20.766
it would have a lot more overhead.
00:10:23.333
In Rust or C++ you can wrap
00:10:25.366
a primitive type in a struct,
00:10:27.400
and do so with no runtime overhead.
00:10:30.300
That's not possible in many other languages.
00:10:36.066
Wrapping numeric types is an important design
00:10:39.200
pattern that's useful in Type Driven Design.
00:10:42.800
Another such a pattern that becomes useful
00:10:45.066
in Rust, is to use enum types
00:10:47.033
and pattern matching to model alternatives,
00:10:49.300
options, results, features and response codes, and flags.
00:10:53.866
This lets the compiler check these types
00:10:56.500
for correctness, and further helps us debug
00:10:59.166
our design before we start running and debugging our code.
00:11:04.766
Sometimes a program has to work with
00:11:06.900
values that might not be present.
00:11:09.333
We can use the Option type to represent these in Rust.
00:11:13.966
For example, if a function might return
00:11:16.100
a value, or might not be able
00:11:17.833
to find that value, such as the
00:11:20.066
lookup() functions shown on the slide,
00:11:22.233
we return an optional result.
00:11:25.400
As we saw in the previous lectures,
00:11:27.600
this is safer than returning an optional
00:11:29.600
null pointer because the compiler forces us
00:11:32.300
to pattern match when using the value
00:11:34.233
and handle both the Some and None cases.
00:11:37.933
It's also more semantically meaningful. It makes
00:11:41.800
the intent clearer in the program.
00:11:44.166
Essentially, it provides machine checkable documentation.
00:11:49.733
It's also possible to use optional values
00:11:52.033
as part of struct definitions.
00:11:54.700
For example, here we see the definition
00:11:57.233
of a network packet format, an RTP
00:11:59.566
header, as shown on the right.
00:12:02.333
This is represented in Rust code is
00:12:04.266
shown on the left, with the definition
00:12:06.600
of the struct RtpHeader type.
00:12:09.533
An RTP header contains an optional field,
00:12:12.133
known as the header extension.
00:12:14.566
We can represent this in the struct,
00:12:16.966
by including an Option type in the
00:12:18.800
struct definition representing that format.
00:12:21.966
Again, this makes the intent clear to
00:12:24.200
both the compiler and to other programmers.
00:12:28.233
In both cases, whether we use an
00:12:30.266
Option as a return value from a
00:12:31.800
function, or as a field in a struct,
00:12:34.333
the compiler enforces that both variants are handled.
00:12:38.500
The compiler enforces that we check both
00:12:40.666
the Some case, where the value exists,
00:12:43.433
and the None case where the field
00:12:45.700
or the value isn't present. We can't
00:12:48.800
accidentally write code that assumes the value
00:12:50.933
is always present and crashes at run time if not.
00:12:57.166
In addition to Option, Rust has a
00:12:59.566
Result type that represents a computation that can fail.
00:13:04.333
For example, the slide shows a load_document()
00:13:07.233
function that returns a result that can
00:13:09.300
either be a Document object, or a database error.
00:13:13.000
In the same way that the Option
00:13:14.933
type encode a better version of the
00:13:16.800
idiom of returning a null pointer on
00:13:18.533
failure, the result type is a better
00:13:20.966
version of exception handling, or of functions
00:13:23.933
that return a sentinel value, such as -1,
00:13:26.333
to indicate an error.
00:13:28.433
And, in the same way that the
00:13:30.366
Option type forces us to pattern match
00:13:32.100
to extract the value, and make sure
00:13:34.366
we consider the case where the value
00:13:35.933
is absent, the Result type make sure
00:13:38.433
that we consider both the success and failure conditions.
00:13:43.000
The only way to get at the
00:13:44.400
result value is by pattern matching.
00:13:47.300
We can either check the Ok() case
00:13:49.266
and retrieve the successful value, or we
00:13:51.733
can check the Err() case and retrieve
00:13:53.700
the failure value. It's not possible to
00:13:57.300
write code that doesn't perform the check
00:13:59.166
– such code won’t compile.
00:14:02.333
The Result type is the equivalent of
00:14:04.366
exception handling in Rust.
00:14:07.133
The difference from exceptions is that it's
00:14:09.300
more explicit.
00:14:11.133
Exceptions can be explicitly thrown at any
00:14:13.400
point in the code, but can also
00:14:15.400
be thrown by any method or function
00:14:16.933
that is called. In general, it’s not
00:14:20.000
possible to know if an operation will
00:14:21.666
throw an exception or not, except by
00:14:24.133
careful reading to the documentation. That a
00:14:27.233
function throws an exception
00:14:28.666
is generally not visible in the code.
00:14:32.133
Results, on the other hand, are explicitly
00:14:34.600
returned from functions. It’s always clear when
00:14:37.666
a Rust function can fail, because it
00:14:39.933
will have a Result type as its return value.
00:14:43.100
As with the Option type, it’s necessary
00:14:45.466
to pattern match on Results to determine
00:14:47.533
if they encode success or failure,
00:14:49.500
and to extract the result value.
00:14:51.966
This forces code to handle both cases.
00:14:56.000
Rust has a shortcut, though, for propagating errors.
00:15:00.433
If we look at the calls to
00:15:02.100
the open_database() and db.load() functions on the
00:15:04.900
slide, we’ll see that they end in
00:15:06.900
a question mark. These functions return a
00:15:09.866
Result type, and the annotation indicates that
00:15:12.966
this should potentially be propagated up the call chain.
00:15:17.633
The compiler expands function or method calls
00:15:20.366
annotated in this way, adding the equivalent
00:15:22.900
of a match statement around them.
00:15:25.733
If the called function returns Ok(),
00:15:27.966
this simply extracts that value and continues.
00:15:31.000
But, if the called function returns an
00:15:33.133
error, then it executes a return statement
00:15:35.633
to propagate that error further.
00:15:38.400
For example, if the open_database() call returns
00:15:41.333
a result indicating an error, the annotation
00:15:44.333
on the call will cause the load_document()
00:15:46.966
function to return at that point,
00:15:49.000
passing the error up to its caller.
00:15:52.700
This has the same effect as throwing
00:15:54.500
an exception, with the error working
00:15:56.566
its way up the call stack until
00:15:58.466
it either hits a match statement that
00:16:00.333
handles it, or until it reaches main(),
00:16:02.166
in which case the program is cleanly
00:16:04.066
aborted if the error is not handled.
00:16:08.900
The option and result types in Rust
00:16:11.266
are very powerful, and help detect common
00:16:13.300
problems at compile time.
00:16:15.933
Enum types are also useful to encode
00:16:18.233
properties of the design that relate to
00:16:20.100
the problem domain. They can often be
00:16:22.800
used to help avoid common anti-patterns in system design.
00:16:27.166
The first of these anti-patterns is known as string typing.
00:16:31.600
String typing is where method parameters,
00:16:34.033
return types, and data values are coded
00:16:36.700
as unstructured strings, rather than as some
00:16:39.200
more appropriate type.
00:16:41.300
For example, it’s the case where strings
00:16:43.500
returned from some network operation, such as
00:16:45.733
HTTP response code, are used directly in
00:16:48.800
the rest of the program, rather than
00:16:50.600
being converted to some structured internal representation.
00:16:54.733
By using an enum, we can represent
00:16:57.366
data such as this, that can take
00:17:00.033
one of several possible values, in a structured way.
00:17:03.400
This has some overhead,
00:17:04.966
because we must define the enum that
00:17:06.633
represents the different states, and convert the
00:17:09.300
string representation into the internal format,
00:17:12.066
but provides some nice properties.
00:17:15.300
It enables exhaustiveness checking. We can be
00:17:18.600
sure our code handles all possible values.
00:17:21.266
And we can be sure the compiler
00:17:22.733
will catch any cases we miss,
00:17:24.566
if new values are introduced and the
00:17:26.500
code needs to be updated to handle them.
00:17:29.466
We get ease of refactoring, since the
00:17:32.100
internal code is decoupled from the external representation.
00:17:35.766
And we make nonsensical values unrepresentable.
00:17:39.966
Only the values encoded into the enum
00:17:42.400
can be passed around internally, and invalid
00:17:45.366
values can’t leak into our program from
00:17:47.600
the rest of the system.
00:17:50.066
Essentially, the types provide a representation and
00:17:53.133
documentation that’s also meaningful to, and can
00:17:56.366
be checked by, the compiler, whereas the
00:17:59.333
string types are only meaningful to the programmer.
00:18:04.733
The second anti-pattern is over-use of boolean flags.
00:18:09.200
The use of boolean flags as arguments to functions
00:18:12.133
obscures meaning.
00:18:14.200
Compare the two examples on the slide.
00:18:17.500
The first, calls file.open(), and passes in
00:18:21.200
a filename and two flags, one true
00:18:23.500
and one false.
00:18:26.000
What those flags mean is entirely hidden,
00:18:28.500
unless you’ve memorised the documentation for the
00:18:30.533
open() function.
00:18:32.900
The second variant performs the same operation,
00:18:35.766
but this time the arguments are encoded
00:18:37.766
as enums rather than booleans. The first
00:18:41.333
argument is an enum with values TextMode
00:18:43.500
and BinaryMode, and the second is an
00:18:46.066
enum with values ReadOnly and ReadWrite.
00:18:49.766
The underlying logic is the same,
00:18:52.033
but the types make the behaviour more
00:18:54.066
obvious. They’re easier for the programmer to read.
00:18:57.600
And they allow the compiler to check
00:18:59.766
that the arguments are passed correctly.
00:19:02.300
In the first version of the code,
00:19:03.966
with the boolean arguments, if the programmer
00:19:06.533
swaps the arguments by accident, then the
00:19:08.633
code will compile fine, but fail at
00:19:10.600
runtime. In the version using enums,
00:19:13.866
the code is both more obvious,
00:19:15.800
and won’t compile if the arguments are
00:19:17.600
passed in the wrong order, because the types won’t match.
00:19:21.166
The blog posts listed on the slide
00:19:23.366
talk about this idea in more detail.
00:19:28.000
The fundamental idea of type driven design
00:19:30.366
is to use the type system to
00:19:31.900
describe features of the system design,
00:19:34.300
so the compiler can help check them for correctness.
00:19:37.900
There’s an up-front cost, of course.
00:19:40.200
You need to define the types.
00:19:43.033
The benefit is that fixing compilation errors
00:19:45.666
is easier than fixing silent data corruption,
00:19:47.933
when the program fails.
00:19:50.266
For small systems, the cost may outweigh
00:19:52.633
the benefit.
00:19:54.200
But, for large systems, compiler enforced consistency
00:19:57.333
checks due to use of types can
00:19:59.700
be a significant win.
00:20:03.733
This wraps up our discussion of design
00:20:05.600
patterns for type-driven design.
00:20:08.166
In the next part, I’ll move on
00:20:09.866
to discuss how state machines can be
00:20:11.600
cleanly represented and checked.
-
S. Luu,
Don’t use booleans, Blog Post, December 2019.
-
Use Enums Not Booleans, C2 Wiki, October 2007.
Part 3: State Machines
The third part of the lecture discusses how state machines can be
implemented. State machines are widely used in the implementation
of device drivers and network protocols, so it's important to be
able to express them cleanly in systems programs. The lecture
reviews two ways of doing this, one implemented using enumerations,
one using structure types, and discusses the trade-offs between them.
00:00:00.458
In this third part of the lecture,
00:00:01.875
I want to discuss state machines.
00:00:04.458
I'll talk about what is a state machine
00:00:06.250
and how state machines can be cleanly implemented in Rust.
00:00:10.291
In particular, I'll talk about
00:00:11.583
two different implementation strategies,
00:00:14.083
one using enum types
00:00:15.625
and one using structs types,
00:00:17.708
and the trade-offs between the two different approaches.
00:00:23.000
State machines are common in systems code.
00:00:26.166
They're frequently used to represent the behaviour
00:00:28.166
of a network protocol,
00:00:29.625
file systems, device drivers, and so on.
00:00:33.542
They model the behaviour of the system as a set of states
00:00:36.417
reflecting the status of the system,
00:00:39.125
transitions between those states
00:00:40.792
triggered by events,
00:00:42.250
and state variables that hold the system configuration.
00:00:46.625
The figure shows an example of this,
00:00:48.750
where the system moves between different states,
00:00:51.458
the yellow boxes,
00:00:52.542
in response to events.
00:00:55.500
Some of those events may be triggered by programmer actions,
00:00:58.583
while others are in response to external events and actions.
00:01:03.417
We see that the system can move through the states
00:01:06.041
to eventually reach the IO_RUNNING state,
00:01:08.875
or can be reconfigured at various points,
00:01:11.250
returning to the IO_CONFIGURE_BEGIN state.
00:01:15.417
The example represents a network device driver,
00:01:17.667
and the details of what's going on aren't important.
00:01:21.291
What matters, though, is the pattern.
00:01:24.166
We see state machines in many systems
00:01:26.750
to represent the behavior of an Ethernet driver,
00:01:29.333
as in the example, or a Wi-Fi interface.
00:01:32.750
To represent the TCP connection establishment handshake,
00:01:35.750
or the state of a file system,
00:01:37.542
or a disk driver, or some other piece of hardware.
00:01:41.750
And it's often useful to formalize the code
00:01:44.041
and explicitly write down the state machine
00:01:46.375
with its various events and transitions,
00:01:48.875
and use this to drive the implementation.
00:01:52.834
The state machine captures the essence
00:01:54.625
of the system's behaviour.
00:01:56.542
It captures the high-level structure of the design.
00:02:00.750
And it should be easy to reason about,
00:02:02.875
to prove properties such as termination,
00:02:05.125
absence of deadlocks,
00:02:06.333
whether all states are reachable, and so on.
00:02:11.250
That said, it can be difficult
00:02:13.458
to cleanly implement state machines in code.
00:02:17.166
The structure of the code often tends
00:02:19.041
not to match the structure of the state machine,
00:02:21.750
and it's often not easy to understand
00:02:23.875
what state the system is in,
00:02:26.125
or to visualize the transitions.
00:02:29.458
This information is often encoded
00:02:31.250
in mutable state variables,
00:02:33.500
hidden in a mass of conditional operations,
00:02:35.875
and spread throughout the code.
00:02:39.458
This makes it difficult to validate
00:02:41.000
the code against the specification.
00:02:43.208
It makes it difficult to check the state machine.
00:02:47.375
Recently though, we've started to see new approaches
00:02:49.792
to modelling state machines in strongly typed
00:02:52.250
functional languages.
00:02:54.166
These make the code clearer
00:02:56.125
and make the state machine more obvious.
00:02:59.583
They encode states and events as enumerations
00:03:02.208
and pattern match on state event tuples.
00:03:06.375
Or they encode states as types and transitions as functions.
00:03:11.166
Or they add first-class state machine support
00:03:13.250
to the language and to its runtime.
00:03:16.708
This latter is shown on the right
00:03:18.375
and is a code fragment taken from a paper about the
00:03:21.041
singularity operating system from Microsoft Research.
00:03:24.959
It's also the approach taken by
00:03:27.083
asynchronous code, often used for concurrency,
00:03:29.667
that we discussed in lecture 7.
00:03:33.417
I'll talk about the other two approaches
00:03:35.125
in the remainder of this lecture.
00:03:40.208
There are two possible state machine implementation
00:03:42.542
strategies that leverage these insights
00:03:44.708
and can be used in Rust.
00:03:47.834
The first is to use enumerated types, enums,
00:03:50.917
to represent the states and the events,
00:03:53.375
and to use functions to represent
00:03:55.041
state transitions and actions.
00:03:58.083
In this approach, you define one enum type
00:04:01.250
to represent all the possible states,
00:04:03.500
and another to represent all the possible events.
00:04:07.792
You define a function that takes a tuple of state and event
00:04:11.417
and returns the next state,
00:04:13.583
encoding the state transitions,
00:04:16.125
and you define a function to represent the action
00:04:18.792
performed on each transition.
00:04:22.583
This approach builds on the intuition
00:04:24.458
that enum types express alternatives,
00:04:27.166
and the idea that a state machine
00:04:28.959
is a set of alternative states
00:04:30.542
with transitions between those states
00:04:32.208
driven by a set of possible events.
00:04:37.250
You start by defining the enums
00:04:39.458
that represent the states and the events.
00:04:42.792
In this example, the enum representing the states
00:04:45.792
is enum ApcState,
00:04:48.083
and that representing the events
00:04:50.083
is the ApcEvent enum.
00:04:53.875
What the system is modelling isn't really important,
00:04:56.667
but we can see from the ApcState
00:04:59.083
that it involves connections,TCP stream objects,
00:05:02.250
and messages that can be sent
00:05:04.583
and received on those connections.
00:05:07.000
It's a network protocol of some sort.
00:05:10.250
And we see that the system has a typical
00:05:12.375
set of states for a network system.
00:05:15.041
It can be initialized,
00:05:16.500
waiting for connections,
00:05:18.083
accepting connections,
00:05:19.542
receiving messages,
00:05:21.000
closing a connection, and so on.
00:05:25.000
Similarly, in the ApcEvent enum,
00:05:27.667
we see a typical set of events for a networked system.
00:05:31.417
A TCP connection has connected,
00:05:33.625
a message has been received,
00:05:35.667
some response is valid, and so on.
00:05:39.792
Both the states and the events are encoded as enums,
00:05:42.792
with parameters to those enums
00:05:44.875
holding state variables that provide additional context.
00:05:51.708
Having defined the enums representing the states and events,
00:05:54.708
you define a function that maps between states.
00:05:59.000
In the example, this
00:06:00.959
function is a method, next(),
00:06:03.792
implemented on the ApcState enum.
00:06:07.375
Its parameters are self,
00:06:09.291
an instance of an ApcState enum
00:06:11.458
representing the current state,
00:06:13.500
and an instance of an ApcEvent object.
00:06:18.250
The function pattern matches on the tuple of self,
00:06:20.959
the current state,
00:06:22.458
and the events that occurred,
00:06:24.417
and returns a new ApcState instance.
00:06:29.500
We see that the body of the function is a table
00:06:31.708
matching the state event tuples
00:06:34.125
that directly encodes the state transitions.
00:06:38.875
The tuple of state and event
00:06:40.750
is matched against a list of states
00:06:42.917
the system can be in, and
00:06:44.792
the events that can occur in those states,
00:06:47.000
and evaluates to a new instance of an
00:06:49.625
ApcState object that's returned by the function.
00:06:54.125
If there's no match,
00:06:55.333
the catch-all at the end of the match statement is taken
00:06:57.792
and the system fails.
00:07:00.750
This gives a very clean representation
00:07:02.917
of the state transition table that's easy to
00:07:05.458
validate against the specification.
00:07:09.583
Importantly, the next() function takes
00:07:12.166
ownership of self,
00:07:14.041
that is the parameter is self
00:07:16.458
rather than &self.
00:07:18.792
As we've seen, this means it consumes the state
00:07:21.625
and returns the new state,
00:07:23.250
enforcing that the transition occurs.
00:07:28.625
The enums representing the states and events,
00:07:31.583
and the state transition function
00:07:33.291
that maps between the states
00:07:35.375
are brought together in a new struct
00:07:37.250
representing the state machine itself.
00:07:41.000
In this example,
00:07:42.208
the ApcStateMachine struct
00:07:44.834
holds the current state and any extra data needed for
00:07:48.417
the system to operate.
00:07:50.083
In this case, a socket address and a timeout.
00:07:54.166
The state machine defines two functions
00:07:57.792
The new() function creates
00:07:59.917
an instance of the state machine in the initial state.
00:08:03.875
The run_once() function
00:08:05.834
performs the actions for the current state.
00:08:08.834
It matches on the value of the current state
00:08:11.708
and any state variables encoded into that enum variant
00:08:15.375
and performs whatever processing is needed.
00:08:19.166
When something happens that could potentially
00:08:21.375
cause the state to change
00:08:22.917
it returns an event that describes what happened.
00:08:27.834
The run_state_machine() function,
00:08:29.959
we see on the right,
00:08:31.417
shows how the state machine is used.
00:08:34.083
It instantiates the APC state machine object
00:08:37.625
and then loops.
00:08:39.667
For each loop it calls the run_once() method
00:08:43.166
to retrieve the next event.
00:08:45.375
Then it calls the next() function on the state,
00:08:47.708
retrieving the next state and storing it into
00:08:50.041
the state machine struct.
00:08:52.333
If the system has entered the finished state,
00:08:54.667
it breaks out of the loop,
00:08:56.708
otherwise it loops around again
00:08:58.417
and processes the next event.
00:09:02.000
The logic needed to control the transition between states
00:09:05.208
is in the parameters of the
00:09:06.667
enums representing the states and events,
00:09:09.875
and the operations performed in each state
00:09:12.750
are written in the branches of the match statement
00:09:15.291
in the run_once() function.
00:09:18.500
This cleanly separates the actions
00:09:20.375
to be performed in each state
00:09:22.000
from the code that manages the state transitions,
00:09:24.959
and it cleanly encodes the state transition logic
00:09:28.041
into a single function.
00:09:30.667
It's a very elegant, easy to check,
00:09:33.792
way of representing state machines.
00:09:40.041
Rust also permits an alternative way to model state machines
00:09:43.375
based around structure types.
00:09:46.667
In this alternative,
00:09:47.959
each state is represented by a struct,
00:09:50.333
one struct per state.
00:09:53.417
Events are represented by method calls on those structs.
00:09:57.583
And state transitions
00:09:59.208
are modeled by returning a struct
00:10:01.083
that represents the new state.
00:10:04.625
This approach builds on the intuition
00:10:06.333
that states hold concrete state,
00:10:08.792
and events are things that happen in states.
00:10:14.542
The code fragments on this slide show an example
00:10:17.125
of the struct-based approach to modelling state machines.
00:10:20.625
There are three possible states this system can be in.
00:10:24.333
It can be an UnauthenticatedConnection,
00:10:27.750
an AuthenticatedConnection,
00:10:30.208
or NotConnected.
00:10:32.500
Each is represented by a struct type.
00:10:36.834
A number of methods are implemented on these structs
00:10:40.208
and the slide shows some of those for
00:10:42.625
for the UnauthenticatedConnection struct.
00:10:46.500
We see that the login() method takes the struct
00:10:48.959
as its self parameter, along with some credentials,
00:10:52.166
and attempts to log in.
00:10:54.792
If it succeeds, the result it returns
00:10:57.542
includes an AuthenticatedConnection object
00:11:00.959
representing the new state.
00:11:03.834
If the login fails, it returns a tuple
00:11:06.417
comprising the current state and an error message.
00:11:10.333
Similarly, the disconnect() method
00:11:12.333
takes self as its parameter
00:11:14.250
and returns a NotConnected struct
00:11:16.333
representing the system in the disconnected state.
00:11:20.041
Each call returns the new state the system is in
00:11:24.667
and due to Rust's ownership rules,
00:11:27.125
that we discussed previously,
00:11:28.875
it consumes the old state enforcing the state transition.
00:11:34.667
One of the strengths of the struct-based approach
00:11:38.041
to building state machines is that it uses
00:11:40.917
Rust's ownership rules to enforce clean state transitions.
00:11:45.792
Each state is represented by a struct
00:11:48.375
and state transitions are represented
00:11:50.250
by method implementations on that struct.
00:11:53.750
Importantly, those methods take ownership of the struct.
00:11:57.667
That is, they consume
00:11:59.083
the state they're transitioning away from,
00:12:01.333
ensuring there are no more references to that state,
00:12:04.000
and any resources they don't explicitly return are freed.
00:12:08.166
The transition methods then return ownership
00:12:10.500
of a value representing the new state,
00:12:12.708
populated with any values that need to be retained
00:12:15.708
from the previous state.
00:12:18.000
For example,
00:12:19.166
the login() method of the UnauthenticatedConnection struct
00:12:22.625
consumes the struct
00:12:24.291
and creates and returns ownership
00:12:26.250
of a new AuthenticatedConnection
00:12:28.750
struct on success.
00:12:31.417
The login() method explicitly copies any
00:12:33.959
data that needs to be retained to the new struct it returns.
00:12:37.250
State that isn't copied over is released.
00:12:40.834
If the login() method fails,
00:12:42.750
it returns a tuple comprising an error
00:12:45.125
and the value of self.
00:12:47.125
That is, after taking ownership of self,
00:12:49.708
it passes it back to the caller when a failure occurs.
00:12:53.625
This keeps the object alive
00:12:55.250
if something goes wrong.
00:12:56.667
The old state becomes the new state.
00:13:00.000
This then is the advantage
00:13:01.458
of the struct-based approach to state machines.
00:13:04.125
It uses Rust's ownership rules
00:13:06.083
to enforce state transitions
00:13:07.834
and to guarantee that resources are cleaned up
00:13:10.750
when the state transition occurs.
00:13:16.417
Which approach to representing state machines is best?
00:13:19.959
It depends on your priorities, of course.
00:13:22.500
The enum-based approach is compact,
00:13:24.834
makes states and events clear in the types,
00:13:27.750
and has a clear state transition table.
00:13:30.667
It's good if the state machine is complex,
00:13:33.458
with many different states and transitions,
00:13:35.792
making it important to be able to easily inspect
00:13:38.417
the state transition table for correctness.
00:13:41.542
It also relies on a language
00:13:43.250
that has expressive enum types to allow its implementation.
00:13:47.792
This approach works well in Rust,
00:13:49.792
Swift, or OCaml, for example,
00:13:52.333
but it's difficult to express in languages with weaker
00:13:54.792
enum types and pattern matching.
00:13:57.959
The struct-based approach encodes states
00:14:00.291
and state transitions in the types,
00:14:02.375
and events as methods on those types.
00:14:04.834
The state transition table is
00:14:06.458
less obviously explicit in the code,
00:14:08.458
since it's encoded in the return types of methods,
00:14:11.875
but when implemented in Rust,
00:14:13.667
the ownership rules cleanly enforce the transitions,
00:14:16.834
and ensure nothing from the previous state
00:14:19.000
is accessible in the new state.
00:14:21.417
Both approaches work well.
00:14:26.458
This concludes our discussion of state machines in Rust
00:14:29.417
and type-driven design more broadly.
00:14:32.542
Type-driven development is an approach to structuring
00:14:35.250
the development process that emphasizes
00:14:37.333
use of the type system to ensure the design is correct.
00:14:41.417
This allows you to incrementally debug the design
00:14:44.417
and, as the code develops, also the implementation,
00:14:47.917
using the compiler as a model checker to ensure consistency.
00:14:53.041
In type-driven design,
00:14:54.625
you proceed by defining the types first.
00:14:57.750
You define specific numeric types
00:15:00.041
to represent the different sorts of numeric values
00:15:02.333
and identifiers your code will work with.
00:15:05.000
You define enum types to represent alternatives
00:15:08.291
and to indicate optional values,
00:15:10.625
results, and errors.
00:15:13.333
And using the types as a guide, you write the functions.
00:15:17.083
You write the input and output types,
00:15:19.208
the function prototypes,
00:15:20.625
and run the compiler to check the design for consistency.
00:15:24.750
Then, gradually you implement the functions,
00:15:27.208
piece by piece, using the structure of the types as a guide.
00:15:32.291
Make state machines explicit,
00:15:34.875
and think about ownership of the data
00:15:36.917
and how it's passed between functions
00:15:38.792
and around in state machines.
00:15:40.834
The Rust ownership rules, and the compiler,
00:15:43.375
will help you check that this is being done
00:15:45.417
correctly and consistently.
00:15:48.333
Importantly, don't think of the types as checking the code,
00:15:52.000
think of them as a plan, a model for the solution.
00:15:55.875
Use the compiler as a tool to debug your design
00:15:59.041
before you run your code.
-
G. Hunt and J. Larus,
Singularity: Rethinking the software stack,
ACM SIGOPS OS Review, 41(2), April 2007.
DOI:10.1145/1243418.1243424
-
A. Hobden,
Pretty State Machine Patterns in Rust,
Blog Post, October 2016.
Discussion
The lecture focussed on type-based modelling and design. It discussed the
concept of using the types to help structure and organise the design of a
system, and model the problem space, and using the compiler to help check
the design for correctness.
The idea is to use types to check the design, debugging before you run
the code. Nonsensical operations shouldn't cause a crash, rather they
shouldn't compile. It's a change of perspective to using the compiler
as a model checking tool that can help validate your design.
Does this approach match the way you have developed programs to date?
Is it feasible in a language such as C, C++, Python, or Java?
What are the advantages, and disadvantages, of this approach to software
development?
The lecture also suggested some concrete ways in which the type system
can help in this modelling: numeric types, options and results, feature
flags, avoiding string typing, and modelling state machines.
From what you have seen so far, does these approaches make sense?
At what point do the benefits of modelling the system and developing
the types outweigh the costs of doing so?
In particular, think about whether the approaches to modelling state
machines seem useful or merely over-complex? Do you see benefits in
the rules around ownership tracking to help enforce the structure of
state machine implementations?