Categories
Java patterns

Pattern Patter: Fake Default Parameters

Summary: Allow languages without default parameters to simulate their use. [Code Pattern]

Example

You want to provide a method to open a file. You always need a filename, but you might have other parameters you occasionally use to specify things like buffering. C++ allows for default parameters to specify a value for when the parameter is omitted; Java does not have this construct.

Forces

  • You want conciseness in the usual case, but occasionally need extra control.
  • You can tolerate some growth in the number of interfaces to the class.
  • The language does not support default parameters.

Resolution

Use method overloading: define two methods with the same name and return type, but different parameters. The methods should have corresponding parameters at the same position (so “default” parameters will be the last ones in the argument list). The simpler method should create the default values, and then call the more complex method with all parameters specified.

Discussion

For example, our open method might take these two forms:

void open (String filename) {
StringBuffer buffer = new StringBuffer (100);
open (filename, buffer);
}

void open (String filename, StringBuffer buf) {
// ...
}

Other Uses

This pattern is used in many places in Java’s AWT: see Graphics.drawImage() or Container.add() for example. The Designated Initializer pattern makes use of this as well (for the special case of constructors).

[Written 12-4-97]