Which naming convention do you use and why?
I like to use employeeNameTextBox, because:
It seems more natural from an English language perspective.
I find it's easier to look up with Intellisense.
The convention is similar to the convention used for events (MouseClickEvent, MouseClickEventHandler) and dependency properties (VisiblityProperty).
Note: I am using the full name rather than an abbreviation (such as "tb"), because it is in line with MS's naming conventions that say to avoid using abbreviations.
http://msdn.microsoft.com/en-us/library/ms229045.aspx
The only reason to use the control type in the name first (textBoxEmployeeName) is for easier grouping with Intellisense (All textbox controls would then show up together). Beyond that, there really is no benefit to using that way. I find the second way (employeeNameTextBox) more readable and prefer that way personally, but a lot of people will still go with the control type first, since that is the way it was done for a long time.
Naming your variables is so important. Thick client view conventions seem to be given the short end of the stick. Here are my thoughts:
Never put getters and setters for actual business values on your view. Don't do this:
public Name EmployeeName { get; set; }
To get or set an EmployeeName, your stateful code should explicitly call a method. Do it this way because it projects that the state is not stored on the view, but can be derived from or transposed to the view:
public void SetEmployeeName(Name employeeName);
public Name GetEmployeeName();
Hungarian notation is stupid. It was useful in languages <= VB6 because they used late binding of variable types. You had to protect yourself because type mismatches were runtime errors, not compile time. Only use txtEmployeeName if you also would use strEmployeeName and intEmployeeNumber.
If prefixing the pattern name isn't consistent with your naming convention, don't do it for the control type (which represents a pattern). If you wouldn't create a commandNameFormatting (instead of nameFormattingComamnd), then don't create a textBoxEmployeeName.
You'll probably need a suffix of some sort, since EmployeeName doesn't sufficiently describe the variable's purpose. An EmployeeName text box's purpose is to receive input. You could call it EmployeeNameTextBox if that makes you comfortable, but it might be better to call it EmployeNameInput. This has the added bonus that if you have a label, it's clear that EmployeeNamePrompt (or EmployeeNameLabel) is not the same as the text box. Without some sort of descriptive suffix, you don't have a good way to differentiate.
I (almost) always use [controltype][descriptive name]. I want to know right away what type of control I'm dealing with when I look at code, and if I DON'T remember the name, intellisense can help me out.
Just using a descriptive name (EmplyeeName) doesn't work for me. What type of control? Is it a label, a text box, or a combo box? Or a string? Or a file? It's important enough that the type of control or variable is always a part of it.
I propose a third option: uiEmployeName. Reasons:
It's not Hungarian. Both of the notations you mention are just flavors of Hungarian.
If you change an employee name text box over to a listbox you don't need to rename your variables.
Everything is grouped nicely in the intellisense without involving the type of the object.
The name of the object closely follows its function. It is a user-facing object that gets the employee name.
I generally try to keep the element type short, followed by a distinguishing label. I find that it quickly communicates the type and purpose of the element:
txtEmployeeName;
lblEmployeeName;
Why not EmployeeName? Seriously how does the control type as part of the name when it is already provided by your IDE assist in delivering easy to maintain code? Consider Ottenger's Rules for Variable and class Naming
K
As I read it, an article linked to in the article mentioned in the question (namely, Names of Resources) does use the control type at the end, in FileMenu (and ArgumentException though it's not a control).
My personal opinion is that this is also more readable, as it's the employee name text box and hence should be named the employeeNameTextBox, just like the words "File menu" are read in that order. (Though I substitute "Edit" for "TextBox" for brevity — I should probably kick that habit to use control names consistently with the environment name for them.)
A MUST READ is the XAML Guidelines released by Jaime:
Also read more here
WPF-specific Answer: No name at all.
Why? Because if you're developing using WPF you should not be naming your controls. If you are, you are doing something wrong.
WinForms required controls to be named because its data binding was so weak. WPF solves all that: The control itself can specify its data and behavior, so there is no need to name it.
I guess it's better to follow Microsoft's Object Naming Convention for naming your controls both in C# as well as Visual Basic.
I don't recommend hungarian notation in any form. textBoxEmployeeName is a form of hungarian notation. So I support the use of employeeNameTextBox.
Personally I don't even bother using the word TextBox, because it is not what is important about the variable. What is important is "Employee" and "Name". Not only does adding the word TextBox lock you in to a certain type, it also make it much harder to change that type, because you need to change the name to normalize your code and make it correct. Say for some reason you started this as a TextBox, but you later received a requirement to change this to a DropDownList or some other type, now you have to update all of your code and JavaScript to make it say DropDownList instead of TextBox.
It is much easier to forget about trying to type your variable names, and just simply name them. You have intellisense and compile time error checking for a reason, why not use it.
I would go with [controlType][DomainTerm] which in this case is textBoxEmployeeName. The reason is that while coding for the C# code behind you are more care about the UI controls than the domain specific terms.UI(View) side coding we need to identify/recognize the control type faster, which is little more important than the domain specific name in the View side , and since we read from 'Left to right' this naming convention is relevant.
I generally use txtEmployeeName or cmpEmployeeType , but textBox instead of txt is preferred as per MS guidelines
I have used both txtEmployeeName and employeeNameTextbox. Like many of the posts indicated, this is helpful for grouping. One groups by control types (txtEmployeeName, txtManagerName) while the other can group different related controls together (employeeNameTextbox, employeePhoneTextbox, managerNameTextBox, managerPhoneTextbox). In many cases I find the later more useful while coding.
You should do whatever it is that makes your code readable and self-documenting. Following hard and fast rules is always a mistake because they almost never cover all aspects of what needs to be done. There is nothing wrong with having guidelines (such as not using Hungarian notation), but it is more important that you are consistent and clear with your naming convention, whatever it is, than you follow some rules found on the Internet.
Ideas:
Avoid encodings/abbreviations.
The name should stand out from
similar names in the same scope.
Make the unique-most part the
left-most part. I suspect you have
several text boxes, but only one is
the employee name.
Avoid needless context. Are all the
names on this page about employees?
Is it an "employee" page? Then
EmployeeName is redundant. NameBox
or NameControl should be plenty.
Avoid needless context: do you have
names that are not controls? If so,
"Box", or "Control" is useful,
otherwise not so much.
Disclosure: I am the "ottinger" from "ottingers naming rules", which also evolved to be chapter 2 of "Clean Code". See short form at http://agileinaflash.blogspot.com/2009/02/meaningful-names.html
In VB I actually like to go with [ControlName]_[ControlType]. I can't remember how I started doing that but I suppose it's because it feels like a logical order. It also simplifies coding a bit because the code suggestions are grouped by the control description rather than the control type.
I name controls the same way in C# except I follow C#'s preference for camelCase: [controlName]_[controlType].
I also tend to use my own abbreviations for control types, though they are not vague.
Examples:
VB: Save_Btn and NewFile_MItem (menu item)
C#: save_btn and newFile_mItem
It works for me, but of course every programmer has their style.
Related
Inside the agent, I have seen uvm_component creation like
apb_monitor m_monitor;
m_monitor=apb_monitor::type_id::create("monitor_name_aaa", this);
m_monitor.analysis_port.connect(analysis_port);
Here we can see that when referring to the hierarchy, we still need to put m_monitor.* rather than monitor_name_aaa.*.
My questions are
What is exactly the purpose of this name property 'monitor_name_aaa'
for?
I have seen in many places people says best way is to put the name = 'm_monitor', same as the m_monitor. If this is true, then why not the methodology just built in this feature directly?
Another point is that If I do get_type_name(), then I see the it is using the name property, like m_env.m_agent.monitor_name_aaa instead.
Thanks!
In UVM it is useful to be able to refer to components either using their SystemVerilog hierarchical name directly or as the string equivalent. (There's the answer to Q1.) Unlike in VHDL, in SystemVerilog there is no way of finding out what the name of a variable is. So, when you create a component, you have to manually set this up. (There's the answer to Q2).
As you point out, you must always make the name of the component the same as the name of the variable pointing to it ("m_monitor" in this case), otherwise you will not have this useful ability to refer to components either by SystemVerilog hierarchical reference or by the equivalent string.
Me and my colleague are developing an ms access based application. We are designing and coding different pages/forms in order to divide work. We plan to merge our work later. How can we do that without any problems like spoiling the design and macros? We are using Ms access 2007 for front end and sqlserver 2005 as the datasource.
I found an idea somewhere on bytes.com. I can import forms, reports, queries,data and tables that I want.I'm going to try this. However, it's just an idea.So, need to study this approach by trial and error techniques.
The most important requirement is to complete the overall design before you start coding. For example:
All the forms must have the same style. Help and error information must be provided in the same way on each form. If a user can divide the forms into two sets, you have failed.
The database design must be finished with a complete, written description of each table, its relationships and its attributes.
The purpose and parameters for each major macro must be defined. If macro A1 exists only to service macro A then A1 is not a major macro and only A's author need know of its details until coding is complete.
Agreed a documentation style and detail level. If the application needs enhancement in six or twelve months' time, you should be able to work on the others macros and forms as easily as on your own.
If one of you thinks a change to the design is required after coding has started, this change must be documented, agreed with the other and the change specification added to the master specification.
Many years ago I lectured on (Electronic Data interchange (EDI). With EDI, the specification is divided into two with one set of organisations providing applications for message senders and another set providing applications for message receivers. I often used an example in my lectures to help my audience understand the importance of a complete, unambiguous specification.
I want two shapes, an E and a reverse-E, which I can fit together to create a 10 cm square. I do not care what they are made of providing they fit together perfectly.
If I give this task to a single organisation, this specification will be enough. One organisation might use cardboard, another metal, but I do not care. But suppose I ask one organisation to create the E and another the reverse-E. How detailed does my specification have to be if I am to get my 10 cm square? I would suggest: material, thickness and dimensions of the E. My audience would compete to suggest more and more obscure characteristics that had to match: density, colour, pattern, texture, etc, etc.
I was not always convinced my audience listened to the rest of my lecture because they were searching for a characteristic that would cap all the others. No matter, I had got across my major point which was why EDI specifications were no mind-blowingly detailed.
Your situation will not be so difficult since you and your colleague are probably in the same room and can talk whenever you want. But I hope this example helps you understand how easy is it for the interface between your two parts to be less than seamless if you do not agree the complete design at the beginning. It's the little assumptions - I though you knew I was doing it that way - that will kill your application.
New section
OK, probably most of my earlier advice was inappropriate in your situation.
So you are trying to modify code you did not write in a language you do not know. Good luck; you will need it.
I think scope is going to be your biggest problem. Most modern languages have namespaces allowing you to give a variable or a routine as much or as little scope as you require. VBA only has three levels.
A variable declared within a function or subroutine is automatically private to that function or subroutine.
A variable declared as Private within a module is invisible to functions and subroutines in other modules but is visible to any function or subroutine within the module.
A variable declared as Public within a module is visible to any function or subroutine within the project.
Anything declared within a form is private to that form. If a form wishes to pass a value to an outside function or subroutine, it can do so by writing to a public variable or by passing it in a parameter to a public function or subroutine.
Avoiding Naming Conflicts within VBA Help gives useful advice.
Form and module names will have to be unique across the merged project. You will not be able to avoid have constants, variables, functions and sub-routines which are visible to the other's functions and sub-routines. Avoiding Naming Conflicts offers one approach. An approach I have used successfully is to divide the application into sub-applications and, if necessary, sub-sub-applications and to assign a prefix to each. If every public constant, variable, function and sub-routine name has the appropriate prefix you can simulate namespace type control.
Throughout Silverlight and WPF, properties that are boolean values are prefixed with Is (almost all), for example:
IsEnabled
IsTabStop
IsHitTestVisible
In all other Microsoft frameworks (winforms, BCL, ASP.NET) Is is not used. What prompted their team to move away from the original naming convention - is it an evolution or a miss-naming that had to stick?
Personally, I always try to prefix boolean values with something that adds a little more meaning (is, has, can, etc.). My usage comes from the following Microsoft guidelines:
Do name Boolean properties with an
affirmative phrase (CanSeek instead of
CantSeek). Optionally, you can also
prefix Boolean properties with Is,
Can, or Has, but only where it adds
value.
MSDN - Names of Type Members
I don't believe this was always the case This wasn't always the case. Those practices date back to .NET 2.0. Before that, things were fair game. Cleaning up those names in newer versions of the Framework, however, would cause all kinds of headaches (hence some of the Framework code uses the convention and some doesn't).
It definitely makes things more readable though. Even using an example from your question. Which would you rather have?
// ambiguous naming, could mean many things
myTab.TabStop
or
// definitely a true/false value
myTab.IsTabStop
The Is prefix can give a hint about the fact that the property only has a get accessor, and, as Thomas and Rachel said, it's a bool. Skip the prefix if you intend to implement both get and set accessors and its type is other than bool.
The Is prefix is part of the official Microsoft Framework Design Guidelines (this does not mean that all MS products adhere to it...).
Personally, I find it useful, if consistently used. It immediately tells you that a Property is a Boolean. You might use it or not, the most important thing is to be consistent about it...
Thomas
Assume, I have a form ...lets say WinForm... with 'n' number of controls.
I populate them with a default value during the LOAD. Then, the user gets to play with all the controls and set different values for the controls and submit the form. Here is where I find myself writing a series of "if" conditional statements handling the value of each of the controls for (but not restricted to) avoiding nulls, doing validation etc.
Though it works, is there some other more efficient way of doing this instead of disparate "ifs" ?
You may not avoid the 'ifs' entirely, but sometimes it helps to gather related bunch of controls on your Form into User Controls. Then you can move the validation and all from the Form class into individual User Controls, thus reducing clutter.
You should know that WinForms has build in facilities for both validation and data binding. Using these built-in capabilities will definitely result in code that is better structured and easier to write and maintain than hand coding data and validation operations. Beth Massi has done a series of videos that demonstrates these features, you can find them on the MSDN web site.
** Edited **
I don't have a catch-all, as this will vary from form to form, but some general advice.
By the way, I love this question because it's all about keeping your code clean, readable, and doing things as simply as possible.
Use the included validation controls when possible rather than writing if statements to validate code. (see instruction video for winforms (based on the question I'm assuming you mean .Net winforms.) here)
Always look to see if you can write a function to handle repetitive tasks. It takes a line of code to call a function, and if your function is only fivelines long, but you call it tentimes, that means you've saved yourself a lot of duplicate lines of code.
If you can write that function to be smart enough and be able to loop through your controls, so much the better.
In short, look at your code and determine to try to do the job with the least amount of code possible while making it easily readable and understandable, and without resorting to bad practices. Experiment in your spare time on non-production "test" code to refine your technique as you learn, but if you get used to thinking about clean code you get better at writing it.
Create a set of Validators to match 1-for-1 with your controls. Derive from the base Validator a ControlXValidator, which take a ControlX as its constructor, and implements isValid() in the special way that ControlX must evaluate as valid, and implements getDiagnosticMessage to display an appropriate message if the validation fails. Then at the end of your form construction code, create a list of Validators containing the Validator subclass for each control.
Then your validateForm() method can just do something like:
allvalid = True;
foreach(Validator vtor in allValidators)
{
if (!vtor.isValid())
{
StatusBar.Caption = vtor.getDiagnosticMessage();
allvalid = False;
break;
}
}
If you are validating by data-type (dates should look like dates), you could use a function that validates your data and pass the function both the user input and a "sample" of valid data. Valid samples could be stored in an array, keyed by the data-type.
And if the data is not valid, the function returns false and you have one if statement that says "if function returns false, punch the user".
Assume a decently strong language:
Create a hash (a.k.a Map) with the keys as the control identities and the values as functions. Retrieve the function and call.
restrict your control.....life in text box you can set limit of inputr chars ...etc....
not specific to any language: use Guard Clauses is usually a good way to get rid ifs. It is a excellent way to check nulls and validations.
I used to have one class for one file. For example car.cs has the class car. But as I program more classes, I would like to add them to the same file. For example car.cs has the class car and the door class, etc.
My question is good for Java, C#, PHP or any other programming language. Should I try not having multiple classes in the same file or is it ok?
I think you should try to keep your code to 1 class per file.
I suggest this because it will be easier to find your class later. Also, it will work better with your source control system (if a file changes, then you know that a particular class has changed).
The only time I think it's correct to use more than one class per file is when you are using internal classes... but internal classes are inside another class, and thus can be left inside the same file. The inner classes roles are strongly related to the outer classes, so placing them in the same file is fine.
In Java, one public class per file is the way the language works. A group of Java files can be collected into a package.
In Python, however, files are "modules", and typically have a number of closely related classes. A Python package is a directory, just like a Java package.
This gives Python an extra level of grouping between class and package.
There is no one right answer that is language-agnostic. It varies with the language.
One class per file is a good rule, but it's appropriate to make some exceptions. For instance, if I'm working in a project where most classes have associated collection types, often I'll keep the class and its collection in the same file, e.g.:
public class Customer { /* whatever */ }
public class CustomerCollection : List<Customer> { /* whatever */ }
The best rule of thumb is to keep one class per file except when that starts to make things harder rather than easier. Since Visual Studio's Find in Files is so effective, you probably won't have to spend much time looking through the file structure anyway.
No I don't think it's an entirely bad practice. What I mean by that is in general it's best to have a separate file per class, but there are definitely good exception cases where it's better to have a bunch of classes in one file. A good example of this is a group of Exception classes, if you have a few dozen of these for a given group does it really make sense to have separate a separate file for each two liner class? I would argue not. In this case having a group of exceptions in one class is much less cumbersome and simple IMHO.
I've found that whenever I try to combine multiple types into a single file, I always end going back and separating them simply because it makes them easier to find. Whenever I combine, there is always ultimately a moment where I'm trying to figure out wtf I defined type x.
So now, my personal rule is that each individual type (except maybe for child classes, by which a mean a class inside a class, not an inherited class) gets its own file.
Since your IDE Provides you with a "Navigate to" functionality and you have some control over namespacing within your classes then the below benefits of having multiple classes within the same file are quite worth it for me.
Parent - Child Classes
In many cases i find it quite helpful to have Inherited classes within their Base Class file.
It's quite easy then to see which properties and methods your child class inherits and the file provides a faster overview of the overall functionality.
Public: Small - Helper - DTO Classes
When you need several plain and small classes for a specific functionality i find it quite redundant to have a file with all the references and includes for just a 4-8 Liner class.....
Code navigation is also easier just scrolling over one file instead of switching between 10 files...Its also easier to refactor when you have to edit just one reference instead of 10.....
Overall breaking the Iron rule of 1 class per file provides some extra freedom to organize your code.
What happens then, really depends on your IDE, Language,Team Communication and Organizing Skills.
But if you want that freedom why sacrifice it for an iron rule?
The rule I always go by is to have one main class in a file with the same name. I may or may not include helper classes in that file depending on how tightly they're coupled with the file's main class. Are the support classes standalone, or are they useful on their own? For example, if a method in a class needs a special comparison for sorting some objects, it doesn't bother me a bit to bundle the comparison functor class into the same file as the method that uses it. I wouldn't expect to use it elsewhere and it doesn't make sense for it to be on its own.
If you are working on a team, keeping classes in separate files make it easier to control the source and reduces chances of conflicts (multiple developers changing the same file at the same time). I think it makes it easier to find the code you are looking for as well.
It can be bad from the perspective of future development and maintainability. It is much easier to remember where the Car class is if you have a Car.cs class. Where would you look for the Widget class if Widget.cs does not exist? Is it a car widget? Is it an engine widget? Oh maybe it's a bagel widget.
The only time I consider file locations is when I have to create new classes. Otherwise I never navigate by file structure. I Use "go to class" or "go to definition".
I know this is somewhat of a training issue; freeing yourself from the physical file structure of projects requires practice. It's very rewarding though ;)
If it feels good to put them in the same file, be my guest. Cant do that with public classes in java though ;)
You should refrain from doing so, unless you have a good reason.
One file with several small related classes can be more readable than several files.
For example, when using 'case classes', to simulate union types, there is a strong relationship between each class.
Using the same file for multiple classes has the advantage of grouping them together visually for the reader.
In your case, a car and a door do not seem related at all, and finding the door class in the car.cs file would be unexpected, so don't.
As a rule of thumb, one class/one file is the way to go. I often keep several interface definitions in one file, though. Several classes in one file? Only if they are very closely related somehow, and very small (< 5 methods and members)
As is true so much of the time in programming, it depends greatly on the situation.
For instance, what is the cohesiveness of the classes in question? Are they tightly coupled? Are they completely orthogonal? Are they related in functionality?
It would not be out of line for a web framework to supply a general purpose widgets.whatever file containing BaseWidget, TextWidget, CharWidget, etc.
A user of the framework would not be out of line in defining a more_widgets file to contain the additional widgets they derive from the framework widgets for their specific domain space.
When the classes are orthogonal, and have nothing to do with each other, the grouping into a single file would indeed be artificial. Assume an application to manage a robotic factory that builds cars. A file called parts containing CarParts and RobotParts would be senseless... there is not likely to be much of a relation between the ordering of spare parts for maintenance and the parts that the factory manufactures. Such a joining would add no information or knowledge about the system you are designing.
Perhaps the best rule of thumb is don't constrain your choices by a rule of thumb. Rules of thumb are created for a first cut analysis, or to constrain the choices of those who are not capable of making good choices. I think most programmers would like to believe they are capable of making good decisions.
The Smalltalk answer is: you should not have files (for programming). They make versioning and navigation painful.
One class per file is simpler to maintain and much more clear for anyone else looking at your code. It is also mandatory, or very restricted in some languages.
In Java for instance, you cannot create multiple top level classes per file, they have to be in separate files where the classname and filename are the same.
(C#) Another exception (to one file per class) I'm thinking of is having List in the same file as MyClass. Where I envisage using this is in reporting. Having an extra file just for the List seems a bit excessive.