C++ Advanced · Lesson 05 of 23
Clean API design
Small interfaces, strong types, const-correctness and hard-to-misuse functions.
Estimated time · 45–75 min
Learning goals
What you will understand
- Explain clean api design in your own words
- Use it in a small robotics example
- Verify the result instead of assuming it worked
Understand the idea first
The mental model
A good API makes correct use easy and incorrect use hard. Use distinct types instead of raw doubles for different units, explicit constructors so a number is never converted by accident, const for anything that does not change, and enums instead of booleans whose meaning is unclear.
Keep the public surface small. Return values instead of using output parameters, document units and error behaviour, and mark results that must not be ignored with [[nodiscard]]. rclcpp's own API follows these habits.
Guided lesson
Work through these steps
- 1.
Read the clean api design example and identify what each line owns or changes.
- 2.
Create a small source file, compile with -std=c++17 and warnings enabled, and run it.
- 3.
Change one input, predict the result before running, then compare the output.
- 4.
Record one compiler or runtime error and explain the correction in your own words.
Worked example
Read it before you run it
struct Meters { explicit Meters(double v) : value{v} {} double value; };
// A distinct type for distances; explicit stops implicit conversion from a plain double.
struct Seconds { explicit Seconds(double v) : value{v} {} double value; };
// A distinct type for times.
enum class Direction { forward, backward };
// Clear names instead of a bool like true/false.
[[nodiscard]] double speed(Meters d, Seconds t) { return d.value / t.value; }
// Units are in the signature and the result cannot be silently ignored.
double v = speed(Meters{2.0}, Seconds{4.0});
// Reads clearly: 0.5 m/s.
// speed(Seconds{4.0}, Meters{2.0});
// Would not compile: the arguments are swapped, so the bug is caught at compile time.
void drive(Direction dir, double speed_mps);
// drive(Direction::forward, 0.5) documents itself; drive(true, 0.5) does not.What the example is doing
- 1.Read declarations from right to left: identify each value's type, name, and initial value.
- 2.Follow the data through each expression before considering syntax shortcuts.
- 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.
Watch it run · Values in memory
See what this code does
The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.
Demo for Clean API design. Expected result: 0.5
Practice code
Now type it yourself
Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice
#include <iostream>
struct Meters {
explicit Meters(double v) : value{v} {}
double value;
};
struct Seconds {
explicit Seconds(double v) : value{v} {}
double value;
};
// TODO: write speed(Meters, Seconds) returning metres per second, marked [[nodiscard]]
int main() {
std::cout << speed(Meters{2.0}, Seconds{4.0}) << '\n';
// speed(Seconds{4.0}, Meters{2.0}); // try un-commenting: the compiler rejects swapped units
return 0;
}Expected output
0.5Stuck? Show the full solution (try it yourself first)
#include <iostream>
struct Meters {
explicit Meters(double v) : value{v} {}
double value;
};
struct Seconds {
explicit Seconds(double v) : value{v} {}
double value;
};
[[nodiscard]] double speed(Meters d, Seconds t) { return d.value / t.value; }
int main() {
std::cout << speed(Meters{2.0}, Seconds{4.0}) << '\n';
// speed(Seconds{4.0}, Meters{2.0}); // try un-commenting: the compiler rejects swapped units
return 0;
}Expected result
How you know it worked
- After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
- Changing the stated input produces the result you predicted.
Practical exercise
Apply the lesson
Redesign move(double, double, bool) into an API using Meters, Radians and an enum class. Write three calls that compile and three misuses that the compiler must reject.
Before you continue
- The program builds with -std=c++17 and no warnings
- You can explain the key rule without reading the example
- The normal and edge cases both have recorded results
If something goes wrong
Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.
Print the inputs and intermediate values, then check conversions, units, and collection order.