Defensive Programming
Optional Results
std::optional represents a result that might not exist.
Optional Results
optional_results.cpp
#include <iostream>
#include <optional>
#include <string>
#include <vector>
std::optional<int> findPrice(const std::vector<std::pair<std::string, int>>& prices,
const std::string& item) {
for (const auto& entry : prices) {
if (entry.first == item) {
return entry.second;
}
}
return std::nullopt;
}
int main() {
std::vector<std::pair<std::string, int>> prices{{"pencil", 2}, {"notebook", 5}};
std::string item = ;
std::optional<int> price = findPrice(prices, item);
std::cout << "item=" << item << std::endl;
if (price.has_value()) {
std::cout << "price=" << price.value() << std::endl;
} else {
std::cout << "price=missing" << std::endl;
}
return 0;
}
#include <iostream>
#include <optional>
#include <string>
#include <vector>
std::optional<int> findPrice(const std::vector<std::pair<std::string, int>>& prices,
const std::string& item) {
for (const auto& entry : prices) {
if (entry.first == item) {
return entry.second;
}
}
return std::nullopt;
}
int main() {
std::vector<std::pair<std::string, int>> prices{{"pencil", 2}, {"notebook", 5}};
std::string item = ;
std::optional<int> price = findPrice(prices, item);
std::cout << "item=" << item << std::endl;
if (price.has_value()) {
std::cout << "price=" << price.value() << std::endl;
} else {
std::cout << "price=missing" << std::endl;
}
return 0;
}
#include <iostream>
#include <optional>
#include <string>
#include <vector>
std::optional<int> findPrice(const std::vector<std::pair<std::string, int>>& prices,
const std::string& item) {
for (const auto& entry : prices) {
if (entry.first == item) {
return entry.second;
}
}
return std::nullopt;
}
int main() {
std::vector<std::pair<std::string, int>> prices{{"pencil", 2}, {"notebook", 5}};
std::string item = ;
std::optional<int> price = findPrice(prices, item);
std::cout << "item=" << item << std::endl;
if (price.has_value()) {
std::cout << "price=" << price.value() << std::endl;
} else {
std::cout << "price=missing" << std::endl;
}
return 0;
}
optional result
An optional result makes the missing case visible without inventing a fake value.