Back
Close

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

adrianimboden
4,784 views

The problem

This example represents a quality checker which may fail to check the quality. The failure is no exceptional case, because it is a normal control flow. Because of that, no exceptions are used here.

The invariant of the quality result is, that always exactly one std::optional must be non-empty.

Example
#include <boost/assert.hpp>
#include <cstdint>
#include <iostream>
#include <optional>
enum class ErrorType {
OutOfRangeForCheck,
Timeout,
};
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

We want to avoid a data structure which has such an invariant, because it is hard to enforce. The calling code has to be written in a defensive way because the invariant is not statically guaranteed.

Try to refactor the example program using std::variant, so that the class ProductProducer never contains unused members.

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