具体类型还是返回类型的接口?

编程入门 行业动态 更新时间:2024-10-26 06:38:58
本文介绍了具体类型还是返回类型的接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

今天,我谈到了对象编程风格,具体类型或接口的基本悖论.

Today I came to a fundamental paradox of the object programming style, concrete types or interfaces.

对于方法的返回类型(具体类型还是接口),更好的选择是什么?

Whats the better election for a method's return type: a concrete type or an interface?

在大多数情况下,我倾向于将具体类型用作方法的返回类型.因为我相信具体类型在将来使用时会更灵活,并且会提供更多功能.

In most cases, I tend to use concrete types as the return type for methods. because I believe that an concrete type is more flexible for further use and exposes more functionality.

这方面的阴暗面:耦合. 天使般的:具体类型本身包含您最初将要返回的接口以及其他功能.

The dark side of this: Coupling. The angelic one: A concrete type contains per-se the interface you would going to return initially, and extra functionality.

你的拇指规则是什么?

对此有任何编程原则吗?

Is there any programming principle for this?

奖金:这是我的意思的示例使用ReadOnlyCollection或IEnumerable公开成员集合?

BONUS: This is an example of what I mean ReadOnlyCollection or IEnumerable for exposing member collections?

推荐答案

我的经验法则:

1)最初,我让该方法返回接口类型,因为如果需要,以后总是很容易将其更改为具体类型.很难反过来.

1) Initially, I have the method return the interface type, because its always easy to change it to the concrete type later if necessary. Harder to go back the other way.

2)即使方法被声明为返回具体类型,我也会对调用者进行编码以在可能的情况下使用接口类型: InterfaceType i = xyz.methodThatReturnsConcreteType();.

2) Even if the method is declared to return the concrete type, I would code the callers to use the interface type whenever possible: InterfaceType i = xyz.methodThatReturnsConcreteType();.

3)我是否拥有调用代码也有所不同(内部和公共API):

3) Whether I own the calling code makes a difference too (internal vs public APIs):

  • 如果我拥有调用所讨论方法的代码(即内部API),那么我将更愿意返回具体类型.
  • 如果我不控制调用此方法的代码(例如,公共API),则更有可能返回接口类型. 返回具体类型是一种承诺,通常来说,我答应的越少越容易.

其他注意事项:

  • 使用接口进行测试可能会更容易,因为我可以使用实现接口的模拟对象.
  • 我想返回一个代理对象(现在我真的很想找借口)
  • Testing may be easier with interfaces since I can use a mock object that implements the interface.
  • There's an outside chance that I would want to return a proxy object (now I'm really reaching for excuses)

总之,

  • 我通常返回接口类型,因为我觉得松散耦合的好处胜过完全访问具体类型的便利.
  • 但是,我不反对在方便性大于松散耦合的好处的情况下,逐案切换为返回具体类型.
  • I usually return the interface type because I feel the benefits of loose-coupling outweigh the convenience of having full access to the concrete type.
  • However, I'm not opposed to switching to return the concrete type on a case-by-case basis whenever the convenience outweighs the benefits of loose-coupling.

更多推荐

具体类型还是返回类型的接口?

本文发布于:2023-11-12 09:42:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581148.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   接口

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!