Mission Impossible / How to create datatypes which cannot contain invalid state
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#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));
}
Enter to Rename, Shift+Enter to Preview
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