11 Functions and coding
This chapter covers
- Choosing the proper parameter type
- Returning multiple values from a function
- Keeping functions succinct and short
- Ensuring function preconditions and postconditions are met
Functions are the heart of modular programming. A function is a named unit of code that can be called multiple times from different places. The design of functions is critical for producing reusable code that is easy to use, meaningful in behavior, and bug-free. Several mistakes are associated with function design and usage. These are heavily oriented toward proper parameter definition and usage. Many other mistakes are common; these should sensitize the developer to be wary of those.
11.1 Design considerations
Functions comprise a name, a parameter list, a return value, and a body. The compiler insists on all four parts yet provides a way to make the parameter list and return value seem optional. Some books call constructors (and destructors, by implication) functions; they are not, technically, but the C++ standard calls them “special member functions.” A constructor and destructor have no return value and do not qualify for function-hood. The parameter list appears optional, since it can be empty, but it still must be specified by empty parentheses. The return value seems optional because the type can be void. However, this is still a type; it is the type that has no value, or its value is the empty set (for set-theoretic fans).