The input arrives from the outside as text, and the text is always wrong in some way that you did not plan for. The patterns that handle this well are well known, and they all have the same shape. You decide where the untrusted data comes in, you turn it into a value that your program can trust, and then you apply the rules to that value.
The previous lesson in this module covered "How Do assert and Error Codes Compare to Exceptions?", and this lesson is the last one in the Exceptions and Robust Code module.
Validate at the boundary
The first pattern is to decide where the untrusted data enters the program, and to check it there and nowhere else.
#include <iostream>
#include <optional>
#include <sstream>
#include <string>
struct Payment {
int amount_cents;
std::string reference;
};
std::optional<Payment> parse_payment(const std::string& reference, const std::string& amount_text) {
int amount = 0;
char extra = 0;
// The stream extraction tells us whether the whole text was a number.
std::istringstream stream(amount_text);
if (!(stream >> amount) || (stream >> extra)) {
return std::nullopt;
}
if (amount <= 0 || amount > 100000) {
return std::nullopt;
}
if (reference.empty() || reference.size() > 12) {
return std::nullopt;
}
return Payment{amount, reference};
}
int main() {
auto good = parse_payment("ref-001", "2500");
if (good.has_value()) {
std::cout << "accepted " << good->amount_cents << " cents\n";
}
auto bad = parse_payment("ref-002", "25x");
std::cout << "rejected: " << (bad.has_value() ? "no" : "yes") << '\n';
return 0;
}The output shows the valid payment accepted and the malformed one rejected.
accepted 2500 cents
rejected: yesAnd notice the check for the trailing character. The extraction of the integer stops at the first character that is not a digit, so you have to check that nothing was left over.
Guard clauses
The guard clauses are the early returns that handle the bad cases first. They keep the happy path unindented.
#include <iostream>
#include <string>
bool apply_discount(std::string& total, double percent) {
if (percent <= 0.0 || percent >= 100.0) {
return false;
}
if (total.empty()) {
return false;
}
// The happy path is not nested inside the checks.
total = total + " (" + std::to_string(percent) + "% off)";
return true;
}
int main() {
std::string total = "100.00";
std::cout << "applied: " << apply_discount(total, 10.0) << '\n';
std::cout << "total: " << total << '\n';
std::cout << "rejected: " << apply_discount(total, 150.0) << '\n';
return 0;
}The output shows the valid discount applied and the out-of-range one rejected.
applied: 1
total: 100.00 (10.000000% off)
rejected: 0Separate parsing from checking
The parsing turns the text into a number, and the checking decides whether the number is allowed. Keeping them apart makes both of them easier to test.
#include <charconv>
#include <iostream>
#include <optional>
#include <string>
#include <string_view>
std::optional<int> parse_int(std::string_view text) {
int value = 0;
const char* first = text.data();
const char* last = text.data() + text.size();
const auto result = std::from_chars(first, last, value);
if (result.ec != std::errc{} || result.ptr != last) {
return std::nullopt;
}
return value;
}
bool is_valid_amount(int amount) {
return amount > 0 && amount <= 100000;
}
int main() {
auto parsed = parse_int("2500");
if (parsed.has_value() && is_valid_amount(*parsed)) {
std::cout << "accepted " << *parsed << '\n';
}
auto bad = parse_int("2500x");
std::cout << "rejected trailing text: " << (bad.has_value() ? "no" : "yes") << '\n';
return 0;
}The output shows the clean number accepted and the trailing text rejected.
accepted 2500
rejected trailing text: yesNormalise before you validate
Normalising first makes the rules that you write afterwards much simpler. You trim the whitespace and you change the case once, and then your rules only have to deal with one shape of the text.
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
std::string normalise(const std::string& text) {
std::size_t start = text.find_first_not_of(" \t\r\n");
if (start == std::string::npos) {
return "";
}
std::size_t end = text.find_last_not_of(" \t\r\n");
std::string trimmed = text.substr(start, end - start + 1);
std::transform(trimmed.begin(), trimmed.end(), trimmed.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return trimmed;
}
int main() {
std::cout << "[" << normalise(" Ref-001 ") << "]\n";
std::cout << "[" << normalise("\t\t") << "]\n";
std::cout << "[" << normalise("ABC") << "]\n";
return 0;
}The output shows the trimming and the lower-casing.
[ref-001]
[]
[abc]Collecting every problem
When the user has to fix the input, it is friendlier to report all of the problems at once instead of making them fix one and come back.
#include <iostream>
#include <string>
#include <vector>
struct ValidationResult {
bool valid;
std::vector<std::string> errors;
};
ValidationResult validate(const std::string& reference, const std::string& amount_text) {
ValidationResult result{true, {}};
if (reference.empty()) {
result.valid = false;
result.errors.push_back("reference is required");
}
if (amount_text.empty()) {
result.valid = false;
result.errors.push_back("amount is required");
}
if (!result.valid) {
return result;
}
int amount = 0;
for (char c : amount_text) {
if (!std::isdigit(static_cast<unsigned char>(c))) {
result.valid = false;
result.errors.push_back("amount must be a number");
break;
}
amount = amount * 10 + (c - '0');
}
if (result.valid && amount <= 0) {
result.valid = false;
result.errors.push_back("amount must be positive");
}
return result;
}
int main() {
ValidationResult result = validate("", "abc");
std::cout << "valid: " << (result.valid ? "yes" : "no") << '\n';
for (const std::string& error : result.errors) {
std::cout << " - " << error << '\n';
}
return 0;
}The output shows both of the problems being reported at once.
valid: no
- reference is required
- amount must be a numberValidating numbers without floating point
You store the money as an integer count of the smallest unit, and you validate that.
#include <iostream>
#include <optional>
#include <string>
std::optional<long long> parse_pence(const std::string& text) {
if (text.empty()) {
return std::nullopt;
}
long long total = 0;
bool seen_point = false;
int decimal_places = 0;
for (char c : text) {
if (c == '.') {
if (seen_point) {
return std::nullopt; // two decimal points
}
seen_point = true;
continue;
}
if (c < '0' || c > '9') {
return std::nullopt; // not a digit
}
if (seen_point) {
++decimal_places;
if (decimal_places > 2) {
return std::nullopt; // more precision than a currency has
}
}
total = total * 10 + (c - '0');
}
if (decimal_places == 1) {
total *= 10; // "12.5" means 1250 pence
}
return total;
}
int main() {
auto good = parse_pence("12.50");
std::cout << "12.50 -> " << good.value_or(-1) << " pence\n";
auto bad = parse_pence("12.505");
std::cout << "12.505 -> " << (bad.has_value() ? "accepted" : "rejected") << '\n';
return 0;
}The output shows the value parsed exactly, in the whole pence, and the over-precise amount rejected.
12.50 -> 1250 pence
12.505 -> rejectedQuick reference
- You validate at the boundary, where the untrusted data comes in, and nowhere else.
- You use the guard clauses so that the happy path stays at the left margin.
- You separate the parsing from the checking, and you test both of them separately.
- You normalise the text first, and then you write the simple rules.
- You collect all of the errors when the user has to fix the input.
- You store the money as an integer count of the smallest unit, and you never as a floating point.
Try it yourself: write a function that takes a reference and an amount as the text and that returns an optional of a payment. Make it reject the empty text, the text with the trailing characters and the amount that is out of range. Then normalise the reference first, so that the rules only have to deal with one shape of the text. Finally, collect the errors instead of returning at the first problem, and print all of them at once.