Loading [MathJax]/jax/output/CommonHTML/jax.js
Back
Close

Mission Impossible / How to create datatypes which cannot contain invalid state

adrianimboden
9,139 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
// { 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_connectedis_sendingis_receiving
falseignoredignored
truefalsefalse
truefalsetrue
truetruefalse

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.
Go to tech.io
codingame x discord
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