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.
Possible solution
1
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
44
45
46
47
// {
enum class ErrorType {
OutOfRangeForCheck,
Timeout,
};
struct ErrorInfo {
ErrorType type;
std::string detailInfo;
};
using Quality = std::variant<uint32_t, ErrorInfo>;
Quality check_quality(uint8_t production_result) {
if (production_result < 10 || production_result > 20) {
return ErrorInfo{ErrorType::OutOfRangeForCheck, "must be x >= 10 and x <= 20"};
}
return uint32_t{production_result} * 2;
}
void print_quality(Quality quality) {
std::visit(
overloaded{
[](ErrorInfo error) { std::cout << "Error: " << error.detailInfo << "\n"; },
[](uint32_t quality) { std::cout << "Quality: " << quality << "\n"; },
},
quality);
}
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
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content