Example 2 demonstrates the principle of least surprise as follows:
#include <iostream>
void add(int a, int &b)
{ b += a; }
int main(void)
{
int a = 41, b = 1;
add(a, b);
std::cout << "The answer is: " << b << ' ';
return 0;
}
As shown in the preceding example, we have implemented the same library API that we implemented in the previous exercise; it is designed to add two numbers and return the result. The issue with this example is that the API is implementing the following:
b += a;
In this example, the principle of least surprise is being violated in two different ways:
- The add function's arguments are a and then b, even though we would write this equation as b += a, meaning that the order of the arguments is intuitively backward.
- It is not immediately obvious to the user of this API that the result would be returned in b without reading the source code.
A function's signature should document how the function will execute using semantics the user is already accustomed to, thus reducing the probability of causing the user to execute the API incorrectly.