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).

11.2 Mistake 82: Using overloaded functions instead of parameter defaulting

11.3 Mistake 83: Failing to use assertions

11.4 Mistake 84: Returning pointers or references to local objects

11.5 Mistake 85: Using output parameters

11.6 Mistake 86: Incorrect use of parameter types

11.7 Mistake 87: Depending on parameter evaluation order

11.8 Mistake 88: Passing excessive parameters

11.9 Mistake 89: Overly long functions with multiple behaviors

11.10 Mistake 90: Overly responsible functions