Example 6

Example 6 demonstrates the principle of least surprise as follows:

#include <iostream>

int add(int a, int b)
{ return a + b; }

int Sub(int a, int b)
{ return a - b; }

int main(void)
{
std::cout << "The answer is: " << add(41, 1) << ' ';
std::cout << "The answer is: " << Sub(43, 1) << ' ';

return 0;
}

As shown in the preceding code, we have implemented two different APIs. The first adds two integers and returns the results while the second subtracts two integers and returns the results. The issue with the subtract function is two-fold:

  • The addition function is in lowercase while the subtraction function is in uppercase. This is not intuitive and users of the APIs would have to learn which APIs are in lowercase and which are in uppercase. 
  • The C++ standard APIs are all in snake case, meaning they leverage lowercase words with the use of _ to denote a space. In general, it is better to design C++ library APIs with snake case as a beginner is more likely to find this intuitive. It should be noted that, although this is generally the case, the use of snake case is highly subjective and there are several languages that do not adhere to this guidance. The most important thing is to pick a convention and stick to it. 

Once again, ensuring your APIs mimic existing semantics ensures the user can quickly and easily learn to use your APIs, while reducing the probability of the user writing your APIs incorrectly, leading to compile errors. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset