Why is it that we need to name our buttons or textboxes (or any object, for that
ID: 3669622 • Letter: W
Question
Why is it that we need to name our buttons or textboxes (or any object, for that matter) with descriptive names? Wouldn't it just be easier to name them btn1, btn2? Or why bother to start our object names with pic, btn, txt, lbl? Isn't that a waste of time? Does it really matter where we put the code? If we want a label to become invisible, does it matter if we place it under the lbl object in the coding window or under a button? Doesn't the enable and visible properties do the same exact thing? What's the point of putting comments in the code?
Explanation / Answer
The reason Visual Studio adds "TextBox1" when you add it to the page is because Microsoft has no way of knowing how you intend to use it. Naming it "Control1" would be too confusing because it could be any number of controls.
Microsoft provides guidance in general for OO naming conventions, but not specifically for naming UI controls. Since UI controls are ultimately variables used in code, they should follow the same convention as any other variable - no hungarian notation prefix.
The main reasons are...
Type of control may change from textbox to listbox, then all associated code will have to be fixed (noted earlier)
Your code should be more concerned with the content of the control and less with what type of control it is. When you are concerned with the type of the control, you start to depend on certain functionalities and you break encapsulation - you should be able to easily swap controls without changing much or any code. (Basic OOP principle)
It is fairly easy to come up with prefixes for the standard controls, but new controls are being developed every day. You may make your own WebUserControl, or you may purchase a set of third party controls. How will you decide which prefix to use for the custom controls? Instead of focusing on the type of control, your code should be concerned with what information is contained in it.
Examples:
txtFirstName => firstName or FirstName
txtState => state or State
cboState => state or State (prime example of changing control types what about lstState or rdoState - they should all have the same name because your code is not concerned about the type of control,rather the state the user selected)
ctlBilling => billingAddress or BillingAddress (custom control - with hungarian notation it is not very evident what the control even is, but with a meaningful name I begin to understand the information contained in it. i.e. billingAddress.Street, billingAddress.FullAddress etc.)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.