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
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 <cstdint>
#include <iostream>
#include <optional>
struct QualityGoal {
int32_t quality_reference;
int32_t maximal_difference;
};
class ProductProducer {
public:
explicit ProductProducer(std::optional<QualityGoal> quality_goal)
: quality_goal_{quality_goal} {
}
bool produce_one(int32_t quality) {
if (quality_goal_) {
std::cerr << "checking quality..." << std::endl;
const auto difference = quality - quality_goal_->quality_reference;
return difference <= quality_goal_->maximal_difference;
}
std::cerr << "not checking quality..." << std::endl;
return true;
}
private:
std::optional<QualityGoal> quality_goal_;
};
void do_one_production_cycle() {
{
// 1 parameters, 0 unused
auto producer = ProductProducer{std::nullopt};
producer.produce_one(5);
}
{
// 1 parameters, 0 unused
auto producer = ProductProducer{QualityGoal{1, 3}};
producer.produce_one(5);
}
}
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content