The capstone brings everything together. It is a command line program that keeps a list of the items in a stock, and it reads and writes a file. The shape of it is the shape of most small real programs, with the model, the repository, the interface and the tests each in their own place.
The previous lesson in this module covered "Which C++ Bugs Appear Again and Again in Code Review?", and this lesson is the last one in the Building Real Programs module.
The model
An inventory record needs an identifier, a name, a quantity and a price, and it needs to be able to say whether it is valid.
#include <cstdint>
#include <string>
struct Item {
std::string sku;
std::string name;
int quantity = 0;
std::int64_t price_cents = 0;
bool is_valid() const {
if (sku.empty() || name.empty()) {
return false;
}
if (quantity < 0 || price_cents < 0) {
return false;
}
return true;
}
std::int64_t total_cents() const {
return static_cast<std::int64_t>(quantity) * price_cents;
}
};The repository
The repository owns the collection, it performs the operations, and it knows how to save and load itself.
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
class Inventory {
public:
bool add(const Item& item, std::string& error) {
if (!item.is_valid()) {
error = "the item is not valid";
return false;
}
if (find(item.sku) != nullptr) {
error = "an item with that SKU already exists";
return false;
}
items_.push_back(item);
return true;
}
bool remove(const std::string& sku) {
auto it = std::find_if(items_.begin(), items_.end(),
[&sku](const Item& item) { return item.sku == sku; });
if (it == items_.end()) {
return false;
}
items_.erase(it);
return true;
}
const Item* find(const std::string& sku) const {
for (const Item& item : items_) {
if (item.sku == sku) {
return &item;
}
}
return nullptr;
}
std::vector<Item> sorted_by_name() const {
std::vector<Item> copy = items_;
std::sort(copy.begin(), copy.end(),
[](const Item& left, const Item& right) { return left.name < right.name; });
return copy;
}
std::int64_t total_value_cents() const {
std::int64_t total = 0;
for (const Item& item : items_) {
total += item.total_cents();
}
return total;
}
std::size_t size() const { return items_.size(); }
const std::vector<Item>& items() const { return items_; }
bool save(const std::string& path, std::string& error) const {
std::ofstream file(path);
if (!file) {
error = "could not open " + path + " for writing";
return false;
}
for (const Item& item : items_) {
file << item.sku << '|' << item.name << '|' << item.quantity
<< '|' << item.price_cents << '\n';
}
if (!file) {
error = "could not write to " + path;
return false;
}
return true;
}
bool load(const std::string& path, std::string& error) {
std::ifstream file(path);
if (!file) {
error = "could not open " + path + " for reading";
return false;
}
items_.clear();
std::string line;
while (std::getline(file, line)) {
Item item = parse_line(line);
if (item.is_valid()) {
items_.push_back(item);
}
}
return true;
}
private:
static Item parse_line(const std::string& line) {
Item item;
std::size_t first = line.find('|');
std::size_t second = line.find('|', first == std::string::npos ? 0 : first + 1);
std::size_t third = line.find('|', second == std::string::npos ? 0 : second + 1);
if (first == std::string::npos || second == std::string::npos || third == std::string::npos) {
return item;
}
item.sku = line.substr(0, first);
item.name = line.substr(first + 1, second - first - 1);
item.quantity = std::atoi(line.c_str() + second + 1);
item.price_cents = std::atoll(line.c_str() + third + 1);
return item;
}
std::vector<Item> items_;
};The command loop
And it is the part of the program that deals with the outside world, so it is where the validation lives.
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split_words(const std::string& line) {
std::vector<std::string> words;
std::istringstream stream(line);
std::string word;
while (stream >> word) {
words.push_back(word);
}
return words;
}
int main() {
Inventory inventory;
std::string error;
inventory.load("inventory.csv", error);
std::string line;
while (std::cout << "> " && std::getline(std::cin, line)) {
std::vector<std::string> words = split_words(line);
if (words.empty()) {
continue;
}
const std::string& command = words[0];
if (command == "quit" || command == "exit") {
break;
}
if (command == "add") {
if (words.size() < 4) {
std::cout << "usage: add <sku> <name> <quantity>\n";
continue;
}
Item item;
item.sku = words[1];
item.name = words[2];
item.quantity = std::atoi(words[3].c_str());
if (inventory.add(item, error)) {
std::cout << "added " << item.sku << '\n';
} else {
std::cout << "error: " << error << '\n';
}
continue;
}
if (command == "list") {
for (const Item& item : inventory.sorted_by_name()) {
std::cout << item.sku << ' ' << item.name << ' ' << item.quantity << '\n';
}
continue;
}
if (command == "remove") {
if (words.size() < 2) {
std::cout << "usage: remove <sku>\n";
continue;
}
std::cout << (inventory.remove(words[1]) ? "removed\n" : "not found\n");
continue;
}
if (command == "save") {
std::cout << (inventory.save("inventory.csv", error) ? "saved\n" : error) << '\n';
continue;
}
std::cout << "unknown command: " << command << '\n';
}
return 0;
}Testing the core
The repository is where the interesting behaviour lives, and it is easy to test because it does not touch the terminal.
#include <cassert>
#include <iostream>
int main() {
int passed = 0;
// A valid item can be added.
{
Inventory inventory;
std::string error;
Item item{"A-100", "Apples", 5, 250};
assert(inventory.add(item, error));
assert(inventory.size() == 1);
++passed;
}
// A duplicate SKU is rejected.
{
Inventory inventory;
std::string error;
Item item{"A-100", "Apples", 5, 250};
assert(inventory.add(item, error));
assert(!inventory.add(item, error));
++passed;
}
// An invalid item is rejected.
{
Inventory inventory;
std::string error;
Item item{"", "Apples", 5, 250};
assert(!inventory.add(item, error));
++passed;
}
// Removing reports whether anything was removed.
{
Inventory inventory;
std::string error;
Item item{"A-100", "Apples", 5, 250};
inventory.add(item, error);
assert(inventory.remove("A-100"));
assert(!inventory.remove("A-100"));
++passed;
}
// The total value is the sum of the line totals.
{
Inventory inventory;
std::string error;
inventory.add(Item{"A-100", "Apples", 5, 250}, error);
inventory.add(Item{"B-200", "Bread", 2, 300}, error);
assert(inventory.total_value_cents() == 1850);
++passed;
}
std::cout << passed << " tests passed\n";
return 0;
}The output shows all five of the tests passing.
5 tests passedThe build and the project layout
The program splits cleanly into a library and an executable, and the tests link against the library.
inventory/
├── CMakeLists.txt
├── include/
│ └── inventory.hpp
├── src/
│ ├── inventory.cpp
│ └── main.cpp
├── tests/
│ ├── CMakeLists.txt
│ └── test_inventory.cpp
└── build/And the top-level build file describes the two targets and the tests.
cmake_minimum_required(VERSION 3.16)
project(inventory LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_library(inventory_core STATIC src/inventory.cpp)
target_include_directories(inventory_core PUBLIC include)
add_executable(inventory_cli src/main.cpp)
target_link_libraries(inventory_cli PRIVATE inventory_core)
enable_testing()
add_subdirectory(tests)And the workflow is three commands.
cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failureWhat a complete program still needs
And there are five things that the capstone above does not have yet, and every real program needs them.
the missing part what it needs
------------------------------ ----------------------------------------------
the prices they are parsed as the cents, never
as a floating point
the errors every command reports a message and
the program carries on
the help a help command that lists the
commands
the atomic saving the file is written to a temporary
name and then renamed
the logging the program says what it did to the
standard error
The checklist for the capstone
- The model holds the data and it knows whether it is valid.
- The repository owns the collection and it does the saving and the loading.
- The command loop only parses the input and it never touches the data directly.
- Every command reports what happened, and the bad input never stops the program.
- The tests cover the repository, and the tests do not need the terminal.
- The build has a library, an executable and a test target.
Quick reference
- The model holds the data and the rules about it.
- The repository owns the collection and it saves and loads it.
- The command loop parses the input and it calls the repository.
- The tests cover the repository because it does not need the terminal.
- The build splits into a library, an executable and a test target.
- The money is always an integer count of the smallest unit.
Try it yourself: build the capstone in three files with the CMake file, and then run the tests. Next, add a command that finds an item by its identifier, and a test for it. Finally, add the help command and check that the unknown command still prints a message and does not stop the program.