我致力于开发外部API.我在我的公共接口中添加了一个方法:
public void AddMode(TypeA mode);
public void AddMode(TypeB mode); // the new method, TypeB and TypeA are not related at all
Run Code Online (Sandbox Code Playgroud)
看起来很不错,直到一次测试破了才通过了null.这使编译器与模糊调用混淆.我通过转换null修复了测试.
不过我的问题是:
设计API时,这种情况下最好的是什么?
编辑:
调用就像这个AddMode(null),不像:
TypeA vl = null;
AddMode(v1); // this doesn't cause a problem
Run Code Online (Sandbox Code Playgroud)
API的设计应使其易于正确使用且难以正确使用.您的API易于正确使用:
AddMode(new TypeA());
Run Code Online (Sandbox Code Playgroud)
编译.
它使用不正确更难:
AddMode(null);
Run Code Online (Sandbox Code Playgroud)
不编译.用户不得不做类似的事情
AddMode((TypeA)null);
Run Code Online (Sandbox Code Playgroud)
哪个应该让他思考,这是否是预期用途.所以我认为你的API是可以的.
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |