Mission Impossible / How to create datatypes which cannot contain invalid state
adrianimboden
826 views
This example implements a serial port protocol which is request/response based. It assumes a that:
- the send and receive is long running
- the current status can be obtained for debugging reasons
- calls to send_request are synchronized by the caller
Example
1
2
3
4
5
6
7
8
9
10
// { autofold
#include <boost/assert.hpp>
#include <iostream>
#include <mutex>
#include <thread>
void long_running_task() {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
// }
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
The problem here is, that we have three bool variables which would result in 2×2×2=8 possible state combinations, of which only 4 are used:
is_connected | is_sending | is_receiving |
---|---|---|
false | ignored | ignored |
true | false | false |
true | false | true |
true | true | false |
This leads to the following results:
- A person which reads the code has to look up all the various asserts in order to understand the existing invariants
- A person which debuggs the code has to keep values of supposedly relevant variables in his head, which are actually not used
- It is very easy for a different programmer to change the code in such a way that the previous invariant is no longer given
Now try to refactor the SerialPort example to use an enum instead.
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD Online Participants