Home > Articles

  • Print
  • + Share This
Like this article? We recommend

Crafting Parameter Lists

Method parameter lists are a deep blend of art and science. There are several conflicting rules that should be applied, and the conflicts should be judged according to the situation:

  • In a very general sense, the most important or unique information should be passed first. For example, if we were passing in a filename and an I/O mode, we would pass them in the classic order imposed by fopen—with the filename first.

  • Where it's logical, you can assign reasonable default values to the formal parameters. Remember that all default parameters must be at the end of the list.

  • If different types may reasonably be passed into a method, you probably want to overload it by specifying multiple definitions. Remember that the method signature (the list of types of the formal parameters) must be different for each, and note that a different return type is not sufficient to establish a different method signature.

  • Because parameters that have defaults can be omitted, you must ensure that the compiler can resolve any ambiguity. Many compilers will not catch this kind of ambiguity unless an actual call is made. In essence, if two methods have the same signature except for one or more default parameters, the defaults can never be used. This, of course, defeats the purpose of defaults. Here's an example:

        int myfunc(char *s, char c='x') {} // First signature
        int myfunc(char *s, int i=0) {}   // Second signature
        // ...
        x.myfunc("hello",'a')        // First function called
        x.myfunc("hello",55)        // Second function called
        x.myfunc("hello")          // Error!
  • Don't forget the power of references. If you want to allow the actual parameter to be changed as a side effect, specify the formal parameter as a reference. Use pointers only if you must (for backward compatibility, for example).

  • Don't forget the power of const, either. You can use it to ensure that the body of a method doesn't change the parameter's value. Also use it at the end of a parameter list to show that the method doesn't alter its receiver.

  • + Share This
  • 🔖 Save To Your Account