Optional Methods



next up previous
Next: Alternate Constraint Mechanisms Up: Language Extensions Previous: Implementations

Optional Methods

In addition to where clauses that apply to an entire interface or class, it is possible to attach where clauses directly to individual methods, a feature originally provided by CLU [L+81]. Any where clause from the header of the class still applies, but additional methods can be required of the parameter type. A method that has additional where clauses is called an optional method, because it can be called only when the actual parameter has the method described by the where clause. If the parameter does not have the required method, the instantiation does not have the optional method. This condition can always be checked by the compiler; no extra runtime work is needed.

Optional methods are handy for constructing generic collection interfaces and classes. For example, a collection might have an output method that is present only if the elements have one too, as shown in Figure 5. The implementation of SortedList.output would use the output method of T to perform its job. The instantiation SortedList[Num] would be legal regardless of whether Num has an output method; however, it would have an output method only if Num had the method.


interface SortedList[T]
          where T { boolean lt (T t); }
{
    . . .
    void output(OutputStream s)
        where T { void output (OutputStream s); }
        // effects: Send a textual representation of "this" to "s".
}

Figure 5: An optional method

CLU also provided the ability to attach additional parameters to individual methods; while this functionality is useful in some cases, it adds substantial complexity to the design and implementation, so we chose to omit it.



Andrew C. Myers, Joseph A. Bank, Barbara Liskov
Copyright © 1996 Association for Computing Machinery