很好的理由接口 [英] Good Case For Interfaces

查看:178
本文介绍了很好的理由接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一家公司,其中一些需要使用接口的理由在我们的代码工作(Visual Studio的C#3.5)。

I work at a company where some require justification for the use of an Interface in our code (Visual Studio C# 3.5).

我想问一个铁包复的接口都需要进行推理。 (我的目标是要证明接口编程的一个正常部分。)

I would like to ask for an Iron Clad reasoning that interfaces are required for. (My goal is to PROVE that interfaces are a normal part of programming.)

我不需要说服力的,我只是需要一个好的论点的说服力使用其他。

I don't need convincing, I just need a good argument to use in the convincing of others.

的一种说法我要寻找的是基于事实,而不是基于比较(即因为.NET库使用他们是基于比较。)

The kind of argument I am looking for is fact based, not comparison based (ie "because the .NET library uses them" is comparison based.)

针对他们的说法是这样的:如果一个类是正确设置(与公共和私有成员),那么一个界面仅仅是额外的开销,因为那些使用类仅限于公共成员。如果你需要有一个由超过1类,那么只需设置继承/多态性实现的接口。

The argument against them is thus: If a class is properly setup (with its public and private members) then an interface is just extra overhead because those that use the class are restricted to public members. If you need to have an interface that is implemented by more than 1 class then just setup inheritance/polymorphism.

推荐答案

代码脱钩。通过编程接口,您使用脱钩从实现接口的代码的接口的代码。这允许您更改执行,而无需重构所有使用它的代码。这可与继承/多态性的同时,允许你使用任何一种交替的可能实现的。

Code decoupling. By programming to interfaces you decouple the code using the interface from the code implementing the interface. This allows you to change the implementation without having to refactor all of the code using it. This works in conjunction with inheritance/polymorphism, allowing you to use any of a number of possible implementations interchangeably.

嘲讽和单元测试。当这些方法都是虚拟的,你在默认情况下得到的接口嘲讽框架是最容易使用。其实,这就是为什么我创建的接口的最大原因。

Mocking and unit testing. Mocking frameworks are most easily used when the methods are virtual, which you get by default with interfaces. This is actually the biggest reason why I create interfaces.

定义的行为可能适用于许多不同的类,允许它们被交替使用,即使有不类之间的关系(比定义的行为除外)。例如,马和一自行车类可以都具有一个骑方法。您可以定义一个接口IRideable定义了乘驾行为,以及使用这种行为可以使用马或自行车对象而不强迫他们之间的不自然的继承任何类。

Defining behavior that may apply to many different classes that allows them to be used interchangeably, even when there isn't a relationship (other than the defined behavior) between the classes. For example, a Horse and a Bicycle class may both have a Ride method. You can define an interface IRideable that defines the Ride behavior and any class that uses this behavior can use either a Horse or Bicycle object without forcing an unnatural inheritance between them.

这篇关于很好的理由接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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