Is there any reason to declare optional parameters in an interface?

后端 未结 5 486
星月不相逢
星月不相逢 2020-12-09 16:16

You can declare optional parameters in an interface method but implementing classes are not required to declare the parameters as optional, as Eric Lippert explained. Conver

5条回答
  •  佛祖请我去吃肉
    2020-12-09 16:56

    If one is designing an interface with a method Foo that takes parameter Bar, and 99% (but not 100%) of calls to Foo pass zero for Bar, one must either:

    1. Include within the interface method overloads which do and do not include parameter `Bar`, thus requiring every implementation of that interface to include an extra method, but freeing callers of the need to specify it.
    2. Only include a method which includes `Bar`, saving implementers the cost of the extra method, but requiring an extra parameter to be included at every call site.
    3. Define the parameter as optional within the interface, thus making things more convenient for both implementers and consumers.

    Option #3 seems most convenient to me when it's workable.

提交回复
热议问题