两种 C# 命名约定:您觉得怎么样?

发布于 2024-07-19 13:15:07 字数 1969 浏览 5 评论 0原文

我怀着复杂的心情练习了两种特定的 C# 编码约定。 我很想听听人们的想法。 它们是:

#1。 在其实例所在的类之后命名实例,驼峰命名法

#2:“匹配属性名称”

原理如下:

#1。 在它的实例所在的类之后命名实例,camelCased

我使用它作为命名约定的默认设置。 当然,也有例外。 但如果坚持使用,它会显着提高代码的清晰度和可维护性。 代码看起来像这样:

var dataConnection = new DataConnection();
//not: var dataConn, dbConn, sqlConn, myDbPickOfTheDay etc.

FileInfo fileInfo = new FileInfo();

Timer timer = new Timer(); 

//etc.

我正处于这样的代码给我带来身体痛苦的时刻:

DataConnection dbConn = new DataConnection();

我无法充分强调这个约定如何消除了变量名游戏的痛苦和愤怒。

这种约定与尝试以试图指示实例正在执行的操作的方式命名事物形成鲜明对比,这相当于尝试创造性地将业务案例嵌入到代码中。 代码有一种被重构的方式,以至于那些原始名称充其量也具有误导性。

对我来说,这个公约是黄金。 它还可以防止对同一事物稍微调整变量名称的可怕做法。

这种惯例在实践中的一个例子是:

class Person { ...
   public string FirstName { get; set; }

//and then
var person = new Person();
person.FirstName = firstName; //where firstName comes from somewhere else.

非常容易阅读。 很无聊。 对于维护代码来说,无聊是件好事。

但是,这个约定让我想到#2:

#2“匹配属性名称”(因为缺乏更好的标题)

下面是一个示例:

public class ShoppingCart { ..
  private Item item;
  public Item Item {  //<---- ?
  get { return this.item; } ...

编译器对此非常满意。 事实上,它公开了一个非常好的接口:

//notice how tempting it is to just say "ShoppingCart cart ... "
ShoppingCart shoppingCart = new ShoppingCart();  
shoppingCart.Item = item;

现在,另一种选择是发挥创意——您实际上需要为 Item 建立两个好的变量名称:公共属性名称和私有成员变量名称。

有多少次你看到这样的情景,只想立即退休?

 public class ShoppingCart { ..
      private Item cartItem;
      public Item ShoppingCartItem { 
      get { return this.cartItem; } ..
  ///....
  ShoppingCart userShoppingCart = new ShoppingCart();
  userShoppingCart.ShoppingCartItem = userSelection;

我对第 1 条约定有足够强烈的感觉,因此我认为我可以接受第 2 条约定。

你怎么认为 ?

I have two specific C# coding conventions I've been practicing with mixed feelings.
I'd be curious to hear what people think. They are:

#1. Name instances after the class it's an instance of, camelCased

#2: "Matching property names"

Here's the rationale:

#1. Name instances after the class it's an instance of, camelCased

I use this as my default setting for naming convention. Of course, there are exceptions. But used consistently it dramatically improves code clarity and maintainability. The code looks like this:

var dataConnection = new DataConnection();
//not: var dataConn, dbConn, sqlConn, myDbPickOfTheDay etc.

FileInfo fileInfo = new FileInfo();

Timer timer = new Timer(); 

//etc.

I'm at the point where code like this causes me physical pain:

DataConnection dbConn = new DataConnection();

I can't stress enough how this convention has taken away the pain and anger of the variable name game.

This convention is in sharp contrast to attempting to name things in ways that try to indicate what the instance is doing, which amounts to trying to creatively embed the business case in code. Code has a way of getting refactored to the point where those original names are misleading at best.

To me this convention is gold. It also prevents the horrible practice of slightly tweaked variable names for the same thing.

An example of this convention in practice is:

class Person { ...
   public string FirstName { get; set; }

//and then
var person = new Person();
person.FirstName = firstName; //where firstName comes from somewhere else.

Very easy to read. Very boring. Boring is good when it comes to maintaining code.

However, this convention leads me to #2:

#2 "Matching property names" ( for lack of a better title )

Here's an example:

public class ShoppingCart { ..
  private Item item;
  public Item Item {  //<---- ?
  get { return this.item; } ...

The compiler is perfectly happy with this. And, in fact, it exposes a very nice interface:

//notice how tempting it is to just say "ShoppingCart cart ... "
ShoppingCart shoppingCart = new ShoppingCart();  
shoppingCart.Item = item;

Now, the alternative is to be creative -- You actually need to drum up two good variable names for Item: the public property name and the private member variable name.

How many times have you seen this and just want to retire immediately?

 public class ShoppingCart { ..
      private Item cartItem;
      public Item ShoppingCartItem { 
      get { return this.cartItem; } ..
  ///....
  ShoppingCart userShoppingCart = new ShoppingCart();
  userShoppingCart.ShoppingCartItem = userSelection;

I feel strongly enough about convention #1 that I think I can live with #2.

What do you think ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

腹黑女流氓 2024-07-26 13:15:11

我非常不喜欢在范围内拥有多个标识符的概念,这些标识符仅在大小写的使用上有所不同; 如果我有我的druthers,使用标识符的代码将被要求使用相同的大写/小写字母组合作为其声明,但代码既不允许在同一范围内声明两个仅大小写不同的标识符,也不允许访问任何与内部作用域中的标识符匹配的标识符(大小写除外)。 尽管我所知道的语言(当然不是 VB 也不是 C#)都没有强制执行此类规则,但符合此类规则编写的代码可以在区分大小写和不区分大小写的语言之间自由移植,而无需重命名标识符。

因此,我不喜欢模式#2。 CLS 合规性要求该样式的任何标识符都限制在 privateinternal 范围内。 由于 vb.net 和 C# 都允许名称以下划线开头,因此如果属性名为 Trait,我认为没有理由优先考虑 trait 而不是 _trait >。 使用后一个名称可以清楚地区分程序员想要写入支持变量的情况和手指在 Shift 键上滑动的情况。

至于模式#1,如果类型或方法的整个目的围绕某种特定类型的单个封装对象进行解析,我更喜欢在字段前加上 my 前缀,或在参数前加上 the< /代码>。 即使在编译器允许实例成员和参数使用相同名称的情况下,使用不同的前缀也可以避免在需要时意外使用一个的可能性。

I strongly dislike the notion of having multiple identifiers in scope which differ only in their usage of upper/lower case; if I had my druthers, code which used an identifier would be required to use the same combination of upper/lowercase letters as its declaration, but code would neither be allowed to declare two identifiers in the same scope which differ only by case, nor access any identifier which would--except for case--match an identifier in an inner scope. Although no language I know of (certainly not VB nor C#) enforces such rules, code written in compliance with such rules could be freely portable between case-sensitive and non-case-sensitive languages without having to rename identifiers.

Consequently, I dislike the pattern #2. CLS compliance requires that any identifiers of that style be restricted to private or internal scope. Since both vb.net and C# allow names to start with underscores, if a property is named Trait, I see no reason to favor trait over _trait. Use of the latter name would clearly distinguish cases when the programmer wanted to write to the backing variable from those where his finger slipped on the shift key.

As for pattern #1, in cases where the whole purpose of a type or method resolves around a single encapsulated object of some particular type, I prefer to prefix fields with my or parameters with the. Even in cases where the compiler would allow the same names to be used for instance members and parameters, using distinct prefixes avoids the possibility of accidentally using one where the other is required.

幻想少年梦 2024-07-26 13:15:10

我一直遵循约定1。 不过,如果有两个并排的对象,我会添加一个额外的限定符。

但话虽如此,强制执行此约定可能会出现问题:

  1. 在特定上下文中,对于 ShoppingCart 对象来说,cart 可能是一个足够好的名称(例如,如果有没有与同一功能中的其他“购物车”混淆)。
  2. 有时,约定可能会完全掩盖所声明对象的目的。 例如,Window ScoreBoard = new Window() 表示我们有一个对象,它确实是一个 Window,但被用作 ScoreBoard。 非常富有表现力。 但按照约定 1,您必须编写 Window window = new Window(),这完全隐藏了此窗口背后的意图。

所以我想说,在任何地方都使用这种命名理念,除非它妨碍了意义或显得要求不合理。

关于约定2,我完全同意。 保持属性名称简洁并让对象名称完成其调用的完整含义是一件优雅的事情。 它与命名良好的对象完美配合。 因此,没有理由回避使用它。

I follow convention 1 all the time. Although, I do add an additional qualifier if there are two objects side by side.

But having said that, making this convention mandatory may be problematic:

  1. In a certain context cart may be a good enough name for a ShoppingCart object (if, for example, there is no other 'cart' in the same function to be confused with).
  2. Sometimes the convention may completely obscure the purpose of the declared object. For example Window scoreBoard = new Window() says that we have an object which is indeed a Window but is being used as a scoreBoard. Very expressive. But following convention 1 you'd have to write Window window = new Window() which totally hides the intention behind this window.

So I'd say use this naming idea everywhere except when it hinders meaning or appears unreasonably demanding.

About convention 2, I totally agree. Keeping property names succinct and letting the object name complete the full meaning of its invocation is an elegant thing. It works perfectly with well named objects. So there's little reason to be shy of using it.

梦一生花开无言 2024-07-26 13:15:10

我通常会遵循约定#1,尽管对于长类名我倾向于只使用类的首字母。 如果我引用多个同一类型的对象,那么我会在类型名称前面加上一个名称,指示它是哪一个或它的用途。

如果有意义的话,我经常使用约定#2。 没有什么比您列出的 cart.ShopingCartItem 示例更糟糕的了,它是 ShoppingCart 的一个属性,这一事实使得属性名称的这一部分完全多余。 不过,我很可能将类命名为 ShoppingCartItem 并将属性命名为 Item。 Item 的名称有点过于通用,而 ShoppingCartItem 则告诉您正在使用的商品类型。

I would normally follow convention #1, although for long class names I tend to just use the initials of the class. If I am referring to more than one object of the same type then I would pre-pend the type name with a name indicating which one it is or what it’s used for.

I quite often use convention #2 if it makes sense. There is nothing worse than having something like the example you listed of cart.ShopingCartItem, the very fact that it is a property of ShoppingCart makes that part of the property name totally redundant. However I would quite likely name the class ShoppingCartItem and the property Item. Item is a little too generic a name whereas ShoppingCartItem tells you what kind of item you are working with.

但可醉心 2024-07-26 13:15:10

我一直这样做 1 并且发现它非常可读。 我对 2 持观望态度。我发现它在某些情况下令人困惑,主要是因为由于标识符相同而很难区分类型和属性。

I do 1 all the time and find it very readable. I'm on the fence with 2. I find it confusing in certain situations, mainly because it's hard to distinguish the type from the property due to the identifiers being identical.

眼中杀气 2024-07-26 13:15:09

第 1 条约定可能会变得令人困惑。 如果您在同一个方法中有两个 FileInfo 对象(例如 Source 和 Target),则需要偏离约定才能命名这两个对象。

变量名称应该易于记忆——向不经意的观察者表明其使用的意图。

也许您对这两种约定的组合感到最满意...例如本示例中的 sourceFileInfo 和 targetFileInfo 。

Convention #1 can become confusing. If you were to have two FileInfo objects in the same method-- say a Source and a Target-- you'd need to deviate from the convention in order to name the two.

Variable names should be mnemonic-- to indicate to the casual observer the intent of its use.

Perhaps you'd be happiest with a combination of the two conventions... such as sourceFileInfo and targetFileInfo, per this example.

因为看清所以看轻 2024-07-26 13:15:09

显然,您不能将项目中的每个 System.String 命名为 string*,但对于您不经常使用的东西,尤其是。 您只需要其中一个,并且其功能在您的代码中从其名称中可以明显看出,这些命名约定是完全可以接受的。

无论如何,它们就是我所做的。

我会为 Timer 对象取一个更具体的名称。 定时器有什么用?
但我肯定会将 DataConnection 命名为 dataConnection。

*即使“字符串”不是关键字...

Obviously, you can't name every System.String in your project string*, but for things you don't use a lot of, esp. things you only need one of, and whose function in your code is obvious from its name, these naming conventions are perfectly acceptable.

They're what I do, anyway.

I would go with a more specific name for, say, the Timer object. What's it a timer for?
But I would definitely name a DataConnection dataConnection.

*Even if "string" wasn't a keyword...

清晰传感 2024-07-26 13:15:07

如果您不知道并且关心的话,C# 已经有一个命名标准

http://msdn.microsoft.com/en-us/library/xzf533w0(VS.71).aspx

另外,再次查看您的约定...这里还有一些更多建议。

  • fileInfo 看起来与 FileInfo 很相似,但它除了它的类型之外没有任何意义,我可以通过将鼠标悬停在类型上或在智能感知中快速获取类型。 我建议用含义和一些上下文(如果有)来命名变量。 remoteWebServerLog、localWebServerLog,甚至是 localWebServerLogFileInfo(如果您喜欢名称中的类型)。

    如果我可以在你写了 6 个多月后回来编写代码时提供任何建议。 您将绞尽脑汁试图找出并追踪所有 dbConn 和 fileInfo 到底是什么。 什么文件? 什么数据库? 许多应用程序都有多个数据库,这是 OrdersDB 的 dbConn 还是 ShoppingCartDB?

  • 类命名应该更具描述性。 与 Item 相比,我更喜欢 ShoppingCartItem。 如果每个 ListBox、DropDown 等都将其集合项命名为“Item”,那么您将与许多命名空间发生冲突,并且将被迫使用 MyNameSpace.ShoppingCart.Item 乱扔代码。

话虽如此……即使经过多年的编码,我仍然搞砸了,并且 100% 的时间都没有遵守规则。 我什至可能使用过 FileInfo fi = ... 但这就是为什么我喜欢我的 Resharper“重构->重命名”命令并且我经常使用它。

in case you were not aware and if you care , C# already has a naming standard

http://msdn.microsoft.com/en-us/library/xzf533w0(VS.71).aspx

Also, looking at your conventions again ... here's some more suggestions.

  • fileInfo looks pretty next to FileInfo but it has no meaning other than it's type which I can quickly get by mousing over the type or in intellisense. I would suggest naming your variables with meaning and some context if available. remoteWebServerLog, localWebServerLog, or even localWebServerLogFileInfo if you like the type in the name.

    If I can hand off any advice from coming back to code you've written 6+ mos later. You will be scratching your head trying to figure out and track down what the heck all your dbConn and fileInfo's are. What file? What db? Lots of apps have several dbs, is this dbConn to the OrdersDB or the ShoppingCartDB?

  • Class naming should be more descriptive. Wwould prefer ShoppingCartItem over Item. If every ListBox, DropDown etc named their collection items "Item" you'd be colliding with a lot of namespaces and would be forced to litter your code with MyNameSpace.ShoppingCart.Item.

Having said all that ... even after years of coding I still screw up and don't follow the rules 100% of the time. I might have even used FileInfo fi = ... but that is why I love my Resharper "Refactor->Rename" command and I use it often.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文