To design interfaces in a way that would be both easy to use and hard to misuse, consider the following exercise. Imagine you are a customer of your interface. You want to implement an e-commerce store that uses your payment gateway, or maybe you want to implement a VR application that connects with the Customer API of the example system we've used throughout this book.
As a general rule regarding interface design, avoid the following traits:
- Too many parameters passed to the function/method
- Ambiguous names of parameters
- Using output parameters
- Parameters depending on other parameters
Why are these traits considered problematic?
- The first one makes it hard to memorize not only the meaning but also the order of the parameters. This can lead to errors in usage, which, in turn, may lead to crashes and security issues.
- The second trait has similar consequences to the first one. By making it less intuitive to use your interface, you make it easier for the user to make mistakes.
- The third trait is a variant of the second one but with an added twist. Not only does the user have to remember which parameters are input and which are output, but it is also necessary for the user to remember how the output should be treated. Who manages the creation and deletion of the resources? How is this achieved? What is the memory management model behind it?
With modern C++, it's easier than ever to return a value that contains all of the necessary data. With pairs, tuples, and vectors, there is no excuse to use the output parameters. Besides all of this, returning the value helps embrace the practice of not modifying the state of an object. This, in turn, reduces concurrency-related problems.
- Finally, the last trait introduces unnecessary cognitive load, which, as in the previous examples, can result in mistakes and eventually failures. Such code is also harder to test and maintain as each change introduced has to take into account all the possible combinations already available. Failure to properly handle any combination is a potential threat to the system.
The preceding rules apply to the external part of the interfaces. You should also apply similar measures to the internal part by validating the inputs, making sure the values are correct and sensible and preventing unwanted use of the services the interface provides.