具体类型还是返回类型的接口? [英] Concrete Types or Interfaces for return types?

查看:93
本文介绍了具体类型还是返回类型的接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

奖金:这是我的意思的示例

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.

这篇关于具体类型还是返回类型的接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆