Naming conventions for controls [closed]

2020-07-29 02:21发布

问题:

While working with VS by default the editor generates this:

<asp:Button ID="Button1" runat="server" Text="Button" />

Now the ID generated is Button1 i.e First letter capital. My questions is what is the best way to name the controls ?

  • SubmitButton

  • btnSubmit

or something else?

Which naming convention is considered good ?

回答1:

btnSubmit is Hungarian notation which I don't personally consider good for UI programming since the type of control is evident directly through its declaration or intellisense in Visual Studio.

SubmitButton is better. Generally it takes a form - Purpose-TypeOfControl

For example

InputLabel
FirstNameLabel
LastNameLabel
CancelButton

This is a good reference: http://10rem.net/articles/net-naming-conventions-and-programming-standards---best-practices

Update: Hungarian notation is also discouraged by stylecop/Fxcop. So its better to not to use entirely.



回答2:

The number one reason is readability. Names should be readable and SubmitButton is far more readable than btnSubmit.

The style btnSubmit is called Hungarian notation. One of the problems with it is that you have to keep inventing prefixes for a new type of control you create. For example if you create a custom control called StocksTrendPlotter you will have to have variables such as stpGraph which is hardly readable.

Check out the disadvantages of the Hungarian notation.



回答3:

The main point of a convention is that it's something shared by other developers on your team, and those that might join the team at a later date. While it's good to make sure you can read your own code 6 months, a year, two years later it's even more important that others can read your code when you've moved to another project. So while there's debate about which convention is most useful/readable the key is to make sure it's applied throughout the team, and that new team members have a reasonable chance of being able to understand it when they're brought on board. Hungarian might not be pretty or particularly readable, but its very widespread and we're all familiar with it - even if we don't like it!



回答4:

The "ux" or "ui" prefix is a common notation as it nicely groups all UI controls in intellisense. Also removing any indication for the control type (e.g. button) from the naming is useful should you swap control types at a later point e.g. uxSalutation which could change from textbox to combobox with limited impact.