c# - 命名约定 : How to name a different version of the same class?

标签 c# .net naming-conventions

我有一个类 MyClass,它在实现中有一个错误。该类是库的一部分,所以我无法更改该类的实现,因为它会默默地更改现有客户端的行为(在这种情况下,客户端可能依赖于该错误:参见示例(https://connect.microsoft.com/VisualStudio/feedback/details/790160/httpclient-throws-operationcanceledexception-insead-of-timeoutexception))

我需要创建包含错误修复的同一类的第二个版本。 我以前见过这样的情况,但我见过的命名总是递增的,例如 MyClass2MyClass3

这些情况可能很少见,但我想知道是否有更好的方法来命名这些“版本化”类。 我想象一个随着时间的推移而增长并具有多个此类的解决方案,这可能会让人非常困惑,尤其是对于库而言。我想象自己必须在 MyClassMyClassV2MyClassV3 等之间做出选择。

最佳答案

在理想情况下,新版本会引入额外的功能,同时仍保持与以前版本 API 的 100% 向后兼容性。不幸的是,理想的世界仍然难以捉摸,而且并不总是能够保持完全的向后兼容性。在这种情况下,版本后缀是合适的模式。

标准的 .NET 命名约定是使用增量编号,如 ClassClass2Class3 等。这来自COM 接口(interface)的命名约定,专为您描述的用例而设计。例如,IHTMLDocument 接口(interface)目前有 8 个版本,从 IHTMLDocumentIHTMLDocument8

Cwalina 和 Abrams 的原始 Framework Design Guidelines 书明确推荐了这种做法,作者是这样说的:

DO use a numeric suffix to indicate a new version of the existing API, if the existing name of the API is the only name that makes sense (i.e., it is an industry standard), and adding any meaningful suffix (or changing the name) is not an appropriate option.

// old API
[Obsolete("This type is obsolete. Please use the new version of the same class, X509Certificate2."]
public class X509Certificate  { ... }

// new API
public class X509Certificate2 { ... }

原始 Windows 团队遵循的旧惯例是将后缀 Ex 添加到 API 的新改进版本,该后缀来自“扩展”一词。然而,这并不能很好地扩展,导致函数容易混淆后缀 ExEx。我认为没有 ExExEx;每个人都害怕接触那些 API。 Framework Design Guidelines 明确建议反对这种做法,那些继续构建 .NET 的人已经吸取了教训:

DO NOT use the "Ex" (or similar) suffix for an identifier to distinguish it from an earlier version of the same API.

[Obsolete("This type is obsolete. ..."]
public class Car  { ... }

// new API
public class CarEx      { ... }     // the wrong way
public class CarNew     { ... }     // the wrong way
public class Car2       { ... }     // the right way
public class Automobile { ... }     // the right way

显然,正如他们最后的代码示例所提示的那样,如果您要在新版本的 API 中添加对特定功能的支持,您最好使用引用来命名新类/接口(interface)到那个特定的功能。

虽然上面几乎只关注类和接口(interface),但相同的逻辑也适用于该类的任何成员函数,这些成员函数可能会在以后的修订版中添加。原始函数可以保留其原始名称,新添加的函数可以使用不同的名称来反射(reflect)其迭代或添加的功能。

关于c# - 命名约定 : How to name a different version of the same class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35776519/

相关文章:

c# - XmlDocument.CreateDocumentType 方法超时

.net - 在 .NET 中使用绝对路径的原因

c# - 用于 Microsoft Word 选项窗口的控件?

c# - csharp中emgucv的全局阈值

list - 对象以 "s"结尾时的命名约定列表

coding-style - 编码公约中首字母缩略词末尾的大写或小写混淆

nhibernate - 如何配置 NHibernate(或 Fluent NHib)以向所有表名添加表名前缀?

c# - 如何分割 '-'前后的字符串

c# - 将 ThreadStatic 字段与任务一起使用

c# - 在主机 ('Anonymous' 上配置的身份验证方案不允许在绑定(bind) 'WebHttpBinding' 上配置的那些 ('Basic' )