Back
Close

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

adrianimboden
840 views

The problem

This example represents a production control thingy, which optionally compares the quality of the produced item to a given reference.

Example
#include <cstdint>
#include <iostream>
class ProductProducer {
public:
explicit ProductProducer(bool quality_check_enabled, int32_t quality_reference, int32_t maximal_difference)
: quality_check_enabled_{quality_check_enabled}
, quality_reference_{quality_reference}
, maximal_difference_{maximal_difference} {
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

The problem here is, that a subset of the state is only used based on never-changing facts. The user of this class has to provide quality reference data, even if that data is not used at all.

When someone tries to change the code later to always use the quality data, he may never be sure if the data passed into the constructor is valid or not. He has to check all calling sites to verify that.

Try to refactor the example program using std::optional, 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