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

adrianimboden
8,855 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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,
};
struct ErrorInfo {
ErrorType type;
std::string detailInfo;
};
struct Quality {
std::optional<uint32_t> result;
std::optional<ErrorInfo> errorInfo;
};
Quality check_quality(uint8_t production_result) {
if (production_result < 10 || production_result > 20) {
return Quality{std::nullopt, ErrorInfo{ErrorType::OutOfRangeForCheck, "must be x >= 10 and x <= 20"}};
}
return Quality{production_result * 2, std::nullopt};
}
void print_quality(Quality quality) {
BOOST_ASSERT(quality.errorInfo || quality.result);
if (quality.errorInfo) {
std::cout << "Error: " << quality.errorInfo.value().detailInfo << "\n";
} else {
std::cout << "Quality: " << quality.result.value() << "\n";
}
}
void do_one_production_cycle() {
print_quality(check_quality(3));
print_quality(check_quality(12));
print_quality(check_quality(17));
}
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.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content