This checkpoint combines today's three ideas in one small type. A Duration holds a number of minutes, and the rule is that every Duration that exists holds 1 through 180. Private members stop outside code from changing it, a private constructor stops outside code from creating a bad one, and a static create factory returning std::optional<Duration> is the only public way in. If the factory is right, the rule holds for every Duration in the program, and no other function ever has to check it again.
That last point is the payoff. A function that takes a Duration instead of an int can skip validation entirely, because the type itself carries the proof. The full Task on Day 7 uses the same structure for its ID, title and state.
Predict and run
The same three ideas, applied to a different type. A Title must hold 1 through 40 characters. What does this print, and which line would fail to compile if you wrote Title forged(""); in main?
#include <iostream>
#include <optional>
#include <string>
#include <utility>
class Title {
public:
static std::optional<Title> create(std::string text) {
if (text.empty() || text.size() > 40) { return std::nullopt; }
return Title(std::move(text));
}
const std::string& text() const { return text_; }
private:
explicit Title(std::string text) : text_(std::move(text)) {}
std::string text_;
};
int main() {
auto good = Title::create("Read");
auto bad = Title::create("");
if (good) { std::cout << good->text() << "\n"; }
std::cout << (bad ? "made" : "refused") << "\n";
return 0;
}Check your prediction
Read
refusedTitle forged(""); fails because the constructor is private; the compiler reports that it is a private member of Title. Inside create the same call is allowed, because create is a member. good->text() calls a member function on the object inside the optional, just as *good reads the whole object. Both are only valid after the if has confirmed the optional holds something. Your Duration follows the same pattern with a number instead of text, and adds an operation that combines two values.
The class has no public default constructor on purpose. Duration d; would need some starting value, and any number picked "for now" (0 is the usual one) is exactly the invalid state the class exists to rule out. Copying is fine: a copy of a valid object is valid, so the compiler-generated copy needs no extra code.
What you will use
- A private constructor.
explicit Duration(int)is reachable only from inside the class. - A static factory.
static std::optional<Duration> create(int)validates, then constructs. - A
constgetter.minutes()reads the value and can be called through aconst Duration&. - An operation that returns a new value.
pluscombines two durations and must not be able to produce an invalid one, so it also returns an optional. assertfrom<cassert>. Each acceptance case becomes a check that stops the program if it fails.
Plan before you type
- Write the class shell: private
int minutes_, a privateexplicitconstructor, and a publicconstgetter. - Write
createwith the guard first and the construction last, so no code path can construct before checking. - Write
plus(const Duration& other) const. Decide how it can guarantee its result obeys the rule without writing the rule a second time. - In
main, assert the four boundary cases: 1 and 180 succeed, 0 and 181 fail. - Assert that 100 plus 80 gives 180 and that 100 plus 81 is empty, then print the results.
Prove it can fail
Break the factory on purpose and run your checks again. Change minutes > 180 to minutes > 181 and the assertion that 181 is rejected must stop the program. Then restore it and make plus build its result directly with the private constructor, skipping the check: the "100 + 81" check must now fail. If your program still prints its success line with a broken factory, your assertions are not testing the rule.
Mistakes worth checking for
Duration bad(500);compiles: the constructor is in thepublicsection. Move it belowprivate:.- The program crashes or prints a random number for a rejected value: the code dereferences the optional without checking it, as in
Duration::create(0)->minutes(). That is undefined behavior; test first. - 181 is accepted or 180 is rejected: an off-by-one comparison. Test the two values on each side of each limit.
pluscan produce 200 minutes: one path to a newDurationskipped the 1 to 180 rule.- A function taking
Durationsilently accepts anint: the constructor lost itsexplicit. That only matters inside the class here, but it is a habit worth keeping.
Practice
Your turn
Build Duration with create, minutes() and std::optional<Duration> plus(const Duration& other) const. Assert that 1 and 180 succeed, 0 and 181 fail, and the value is readable through a const Duration&. Then print:
1 and 180 accepted
0 and 181 rejected
100 + 80 = 180
100 + 81 rejected
Factory checked#include <cassert>
#include <iostream>
#include <optional>
// Write Duration here.
int main() {
// Check the boundaries, then try plus.
return 0;
}Hint 1: the idea
Every successful construction must pass through one validation rule. plus is just another way of asking for a new Duration, so it should ask create.
Hint 2: a first step
Write the assertions for plus first: two valid durations whose sum is at most 180, and two whose sum is over 180. Give plus a body that returns std::nullopt and run: the valid-sum assertion fails first, and assert stops there, so move it below the over-180 one if you want to see that one pass. Then ask which existing member already knows the rules a sum must meet. Inside a member function you may read the private members of another object of the same class.
Show one solution
#include <cassert>
#include <iostream>
#include <optional>
class Duration {
public:
static std::optional<Duration> create(int minutes) {
if (minutes < 1 || minutes > 180) { return std::nullopt; }
return Duration(minutes);
}
int minutes() const { return minutes_; }
std::optional<Duration> plus(const Duration& other) const {
return create(minutes_ + other.minutes_);
}
private:
explicit Duration(int minutes) : minutes_(minutes) {}
int minutes_;
};
int main() {
const auto first = Duration::create(1);
const auto last = Duration::create(180);
assert(first && first->minutes() == 1);
assert(last && last->minutes() == 180);
const Duration& view = *last;
assert(view.minutes() == 180);
std::cout << "1 and 180 accepted\n";
assert(!Duration::create(0) && !Duration::create(181));
std::cout << "0 and 181 rejected\n";
const auto hundred = Duration::create(100);
const auto eighty = Duration::create(80);
const auto eighty_one = Duration::create(81);
assert(hundred && eighty && eighty_one);
const auto full = hundred->plus(*eighty);
assert(full && full->minutes() == 180);
std::cout << "100 + 80 = " << full->minutes() << "\n";
assert(!hundred->plus(*eighty_one));
std::cout << "100 + 81 rejected\n";
std::cout << "Factory checked\n";
return 0;
}1 and 180 accepted
0 and 181 rejected
100 + 80 = 180
100 + 81 rejected
Factory checkedEvery dereference (*last, *eighty, full->minutes()) comes after an assertion that the optional holds a value, so in this test none of them can read empty storage. That relies on the assertions running: a build with NDEBUG removes them, and production code should test the optional with if instead. plus reuses create, which means the 1 through 180 rule exists in one line of code and every path to a new Duration goes through it. Day 2 gives these values a stable identity, so a program can find and update one task among many.
Completion is saved in this browser only. It does not measure mastery.