Control/variable naming conventions in ASP.NET - c#

I think the main distinction in naming is between logic and view-related objects. You might have a variable named “UserName” in the code behind file of a page, but then also a .NET TextBox in which a user is supposed to enter their username (a sensible ID would also be “UserName”). How can we differentiate (ID-wise), between the logic “UserName” and the view “UserName”. My question is, what is a sensible distinction to make when coming up with these names?
In my opinion, a variable name/control ID should never describe what it IS, only what it DOES. “tbUserName” describes that it is a TextBox, “strUserName” defines that it is a string.
One idea would be to prefix all view related objects with “vwUserName” and keep the logic part as “UserName”. Does that make sense? What about when we have a situation where you have validators? Would you name them “vwUserNameRequiredValidator”, or “vwEmailAddressFormatValidator”? In that situation would you need to describe what it actually is? Would you give a .NET RequiredFieldValidator object an ID of “rfvUserName”?
I really want to get an idea of what other people think on this, because I want to come up with a sensible and consistent naming convention system going forward. I’m interesting to hear arguments for any type of system.

Hungarian notation is so 1990s... ;-)
I would use UserName for logic and userName for id.

I tend to use _userName as a variable and UserName as property in code behind, and as ID for a text box UserNameField. I find it easier to work with the intellisense in this way, instead of prefixing as we did in the VB-days with txtUserName.
Edit: not calling it UserNameTextBox, but UserNameField is also easier to work with if you want to the exchange the field (that is TextBox) to another control (it may not apply to this example of username though.

For controls, I always add a prefix like:
Textbox - txtName - I don't use tb because it can be confusing since I use tbl for HtmlTable
Checkbox - cbIsNameRequired
RequiredFieldValidator - rfvName
For variables:
Name
IsNameRequired
etc..
It is all about getting used to a pattern but always have a pattern..

Related

Structured code for limiting what values you can set for a property

What would be the correct (and best) way to code in limits as to what values a property can get?
For example, suppose I have the following simple class:
Public Class MyClass
Public Property MyDate As Date
Now, suppose MyDate gets set at run-time, but can't take any values less than a year ago.
Is it correct to throw an exception in the MyDate's setter and then program this in my main module in a Try...Catch fashion and then alert the user if the value is bad or is there a better way to do this?
I'm sure this is a stupidly simple question, but I just want to make sure I'm doing this according to best programming practices.
Yes, throwing and exception is a good idea. ArgumentOutOfRangeException seems to be the best in that situation. Following the MSDN:
The exception that is thrown when the value of an argument is outside
the allowable range of values as defined by the invoked method.
While throwing an exception is a valid option, I recommend against it. The reason is that when a programmer sets a property he/she expects very little to happen other than the value being set. In this case I'd recommend using a set function instead of a property or having the value passed as part of the constructor (where programmers expect validation logic of this sort to happen).
Check this article out. It gives an overview of Validators in the System.ComponentModel.DataAnnotations namespace. They are attributes for your model that support validation.
http://stephenwalther.com/archive/2008/09/10/asp-net-mvc-tip-43-use-data-annotation-validators.aspx
ASP.NET MVC supports surfacing those validations on forms using JS, but in other applications types you can read the attributes from the model itself and enforce the validations.

C# construction objects with builder

Fluent builder is a well-known pattern to build objects with many properties:
Team team = teamBuilder.CreateTeam("Chelsea")
.WithNickName("The blues")
.WithShirtColor(Color.Blue)
.FromTown("London")
.PlayingAt("Stamford Bridge");
However, using it doesn't seem very clear to me due to one particular reason:
Every Team object has its minimal operational state, in other words, set of properties which have to be set (mandatory), so that the object is ready to use.
Now, how should the Fluent builder approach be used considering that you have to maintain this state?
Should the With_XYZ members modify the part of the object, that can't affect this state?
Maybe there are some general rules for this situation?
Update:
If the CreateTeam method should take the mandatory properties as arguments, what happens next?
What happens if I (for example) omit the WithNickName call?
Does this mean that the nickname should be defaulted to some DefaultNickname?
Does this mean that the example (see the link) is bad, because the object can be left in invalid state?
And, well, I suspect that in this case the fluent building approach actually loses it's "beauty", doesn't it?
CreateTeam() should have the mandatory the properties as parameters.
Team CreateTeam(string name, Color shirtColor, string Town)
{
}
Seems to me the points of Fluent Interface are:
Minimize the number of parameters to zero in a constructor while still dynamically initializing certain properties upon creation.
Makes the property/ parameter-value association very clear - in a large parameter list, what value is for what? Can't tell without digging further.
The coding style of the instantiation is very clean, readable, and editable. Adding or deleting property settings with this formatting style is less error prone. I.E. delete an entire line, rather than edit in the middle of a long parameter list; not to mention editing the wrong parameter

C# and Windows Forms control naming guidelines

Does anyone have any guidelines/best practices for naming conventions for Forms and controls (e.g., events, buttons)?
I usually use Systems Hungarian notation
Example:
btnSubmit: is button
lblAccountNum : variable is a label
In WinForms I usually use suffixes, so for example:
submitButton
accountNumberLabel
etc.
But a lot of companies still use a prefix, like anthares said.
I don't believe any special rules are needed for forms development; the Microsoft .NET naming guidelines cover it.
I name forms like any other class in the application: MainForm, SaveDialog, etc.
I name controls like any other field within a class: okButton, nameTextBox, etc.
I usually prefix the full class name e.g. textBoxName. I find it easier to read than three letter prefixes and it's consistent with the names that are generated by the IDE. I only name controls that are referred to by code. Controls that are databound usually don't need a name.
The following example is most of the .net programmer is used
Control: Label
Prefix : lbl
Example: lblFirstName
The reason that the prefixes are not the full class names in most of the companies but some abbreviations of the class name are as follows:
Most of the naming conventions are approved before Visual Studio 2010.
All Visual Studio versions before 2010 have their inteli sense filter with something like "starts with" instead of contains.
That's why a lot of people / architects / leaders decided it will be a better idea to type "txt" and inteli sense will filter all textboxes for you, so then you just type "E" for example and you get txtEmail. If you have the full class name, you will need to type "textBoxE" to get the same result in inteli sense. This adds a lot of overheat when you have complex UI.
Now with Visual Studio 2010 you get a better inteli sense so you can just type "em" and you can easilly see the "textBoxEmail" in the list (along with Email and some other things that contain "em"). Still I seem to prefer to have 2-3 or up ot 4 letters abbreviation that will allow me to filter in inteli sense by control type (specially for UI) than having to type textBox. The reason I prefer it is that even if you are puzzled for a while with some control type (e.g. "rg" for RadGrid) you will need 5 minutes 3-4 times to remember it and start typing without thinking about it. While if you have radGrid everywhere you will need to hit 7 strokes to get to the meaningful one that will filter for you (e.g. "radGridC" in "radGridCustomers").
I do agree that only naming controls that are referenced in the code is usually enough.

Validationattribute only when value is changed?

I want to write a custom ValidationAttribute that checks if the given value is unique or not.
The problem is that in the edit screen, it is not guaranteed that the user actually changed the value, resulting in a false error.
Is there a way to check in my attribute whether the value actually changed? Or can I trigger the attribute only when the value has changed?
I'm getting the feeling this requirement maybe just doesn't belong in an attribute?
When you say ValidationAttibute, do you mean using DataAnnotations? If so, then all of this applies, else, sorry, I misunderstood and only part of this will.
I think your best bet is to do this in the repository or BLL using your unique key for the record, at least this is how I did it. Get the previous values of the record and see if they changed. If they did change, then run your uniqueness checks.
If you can get this logic into the ValidationAttribute, then more power to you, but I am not sure if a validationAttribute would be the best thing since there are ways to get around them. From my understanding of these attributes, you should use them as supplements only to business logic validations and not as the only way that you validate your model.
See here for more info on DataAnnotations
EDIT:
Fair enough, now let's see if I can give an answer to help you :) Check out this link, it is the code for uniqueness checking on any property in any table. Pretty in-depth LINQ to SQL stuff, but looks like it works well. You should be able to decorate any property with this just like using the <Required> or <StringLenght> attributes.
ASP.NET Forums

Web GUI design issue

I'm writing a page with several text fields and a drop down. The fields in the drop down affect the value of the text fields.
For example: the drop down options are "a" and "b". The text fields are "name" and "last name". When choosing "a", "name" is filled with "Joe". When choosing "b", "name" is filled with "Bob".
I've written a class which contains the drop down display name and the values for "name" and "last name".
The question: Design-wise, what's the correct solution - having the class change the text fields, or changing the text fields externally and only accessing the class' data?
Thanks.
P.S - I'm using ASP.Net and Javascript, but this is more of a design issue and not language dependent.
Why do you need to populate an input field with the results of a SELECT change? Can't you get your value directly from the SELECT? What do you do if the user changes the result in the input field? The rule I follow is, if the user is allowed to enter any input, use an input text field. If the user is limited to an array of choices, use a SELECT (or possibly a radio button group).
If it is a long list of choices (longer than your example by a couple orders of magnitude), you can include a filter input where the user can type a few letters and pare the options down to a manageable level, but that is the only case I can think of where you'd want to go the other way with it.
Of course, there may be additional information that's on your mind but haven't imparted here. If so, please elaborate.
Since the class contains all three controls, it is correct that it change the text fields, as it is internal behavior to the class. Now if the fields were all separate classes then it would make more sense to manipulate them externally.
If those select fields and text fields combined work as maybe a widget, then it makes much sense to package them as such in a Class like you have already done. Then as Justin said, operations on these controls should be managed by your class, including keeping all fields synchronized.
If there are enough such widgets to care about, then I'd consider separating the data part of it from the views. Maybe create an additional class that represents the data, and pass an object of that data class to the widget. But pragmatism always comes first.

Categories

Resources