接口和版本控制

时间:2020-03-05 18:48:00  来源:igfitidea点击:

我正在设计一个新的系统,并且随着系统的发展,我将拥有很多接口。命名此接口的最佳实践是什么

ISomethingV01
ISomethingV02
etc

而我这样做

public interface ISomething{
      void method();
}

那么我必须添加方法2,那么现在我该怎么办?

public interface ISomethingV2:ISomething{
      void method2();
}

或者其他相同方式?

解决方案

回答

接口的目的是定义类型必须实现的抽象模式。

最好将其实现为:

public interface ISomething

public class Something1 : ISomething
public class Something2 : ISomething

通过创建同一接口的多个版本,我们不会获得任何代码可重用性或者可伸缩设计的形式。

回答

我不知道为什么人们对帖子不满意。我认为良好的命名准则非常重要。

如果需要保持与上一版本的兼容性。同一接口的版本考虑使用继承。
如果我们需要引入新版本的接口,请考虑以下规则:

Try to add meaningful suffix to you
  interface. If it's not possible to
  create concise name, consider adding
  version number.

回答

理想情况下,我们不应该经常更改界面(如果有的话)。如果确实需要更改接口,则应重新考虑其用途,并查看原始名称是否仍然适用于该接口。

如果我们仍然觉得接口会发生变化,并且接口变化很小(添加项)并且可以控制整个代码库,那么我们应该修改接口并修复所有编译错误。

如果更改是接口使用方式的更改,那么我们需要创建一个单独的接口(最可能使用不同的名称)以支持该替代使用模式。

即使最终创建了ISomething,ISomething2和ISomething3,接口的使用者也很难确定接口之间的区别。他们什么时候应该使用ISomething2,什么时候应该使用ISomething3?然后,我们必须进行废弃ISomething和ISomething2的过程。

回答

我同意Garo Yeriazarian的观点,更改界面是一个严肃的决定。另外,如果我们想推广使用新版本的界面,则应将旧版本标记为过时。在.NET中,我们可以添加ObsoleteAttribute。

回答

我认为我们正在颠覆界面。

迈尔和马丁告诉我们:"可以扩展,但可以修改!"

然后Cwalina(等)重申:

从框架设计准则...

In general, classes are the preferred
  construct for exposing abstractions.
  The main drawback of interfaces is
  that they are much less flexible than
  classes when it comes to allowing for
  evolution of APIs. Once you ship an
  interface, the set of its members is
  fixed forever. Any additions to the
  interface would break existing types
  implementing the interface.
  
  A class offers much more flexibility.
  You can add members to classes that
  have already shipped. As long as the
  method is not abstract (i.e., as long
  as you provide a default
  implementation of the method), any
  existing derived classes continue to
  function unchanged.