As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
As a beginning programmer, I'm trying to settle on a standard naming convention for myself. I realize that it's personal preference, but I was trying to get some ideas from some of you (well a LOT of you) who are much smarter than myself.
I'm not talking about camel notation but rather how do you name your variables, etc. IMHO, var_Quantity is much more descriptive than Q or varQ. However, how do you keep the variable from becoming too long. I've tried to be more descriptive with naming my controls, but I've ended up with some like "rtxtboxAddrLine1" for a RadTextBox that holds address line 1. Too me,that is unmanageable, although it's pretty clear what that control is.
I'm just curious if you have some guides that you follow or am I left up to my own devices?
Some basic rules can be found here. And much more extended rules can be found here. These are the official guidelines from the Microsoft framework designers.
As for your example, the variable should should be called simply quantity.
In this case, I think you'd be better off naming it as primaryAddressLine or firstAddressLine. Here's why - rtxt as a prefix uselessly tells you the type. Intellisense will help you with the type and is immune to changes made to the actual object type. Calling it firstAddressLine keeps it away from the (poor) convention of using 1, 2, 3...on the end of variable names to indicate that for some reason you needed more of them instead of a collection.
Name it for what it represents/how it's meant to be interpreted or used not for its data type, and in naming it don't abbreviate if you don't need to.
The Guidelines for Names is the best starting point. But as in other areas of life, once you know the rules, you begin to know where it's reasonable to break them.
I never use the old Hungarian notation that calls things strFirstName, intCount, and the like; but I still use it on controls: txtFirstName, btnVerifyData, etc. Reasons include:
I'm not that likely to change the type of a control
If I do change the type of a control, I'll have to change a lot of things, not just the name, so changing the name too is no big deal
They're far easier to find with Intellisense.
In addition, I'm quite likely to do the same thing to many of the TextBoxes or ComboBoxes on a page or form, whereas I'm not likely to do something to all the ints or strings referred to on a page or form. So it helps to be able to quickly find all the TextBoxes with their txt prefix.
There are others, though, that adamantly oppose Hungarian even in this case, and I'm sure they have their reasons. Regardless of your personal style, you may find yourself working on a team that has a very different style. In which case, just do what they do; it's very, very rarely worth making an issue of it. The only time I'd do so is if their style leads to a lot of bugs, but off the top of my head I can't think of a case that would cause that.
There are a few good coding standards documents available online - David Lance wrote one:
http://weblogs.asp.net/lhunt/attachment/591275.ashx
I'd recommend that you use Microsoft's own guidelines as a starting point. Typically, most companies start there (in my experience, anyway).
http://msdn.microsoft.com/en-us/library/czefa0ke(VS.71).aspx
The more descriptive the better, you will find that the length isn't as important as remembering what that control/variable did five years down the road.
For .NET API design (and some general C# guidelines) check Krzysztof Cwalina and Brad Abrams' Framework Design Guidelines
Regards,
tamberg
I generally try to follow the microsoft guidelines, with a few very old habits thrown in.
So, I still can't get out of the habit of prefixing privates with an underscore _privateMember.
I'm old, and that got burnt into my brain.
As far as prefixing control widgets, I have found that if you get too descriptive, it can become painful, in the case of changing the UI down the track.
e.g. you have something called ddlProductLine for a dropdown list, and then that has to change to a radio button group, your prefixing convention starts to be more PITA than helpful.
When you have a lot of widgets to work with, sometimes a more generic prefix like uiCtl can help with the clutter, but still make sense if you have to change widget type.
Related
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I am new to C# and have to maintain a C# Application.
Now I've found a method that has 32 Parameters (not auto-generated code).
From C/C++ I remember the rule of thumb "4 Parameters". It may be an old-fashioned rule rooting back to old 0x86 compilers, where 4 Parameters could be accommodated in registers (fast) or on stack otherwise.
I am not concerned about performance, but I do have a feeling that 32 parameters per functions are not easy to maintain even in C#.
Or am I completely not up to date?
What is the rule of thumb for C#?
Thank you for any hint!
There is no general consensus and it depends on who you ask.
In general - the moment readability suffers, there are too many...
Bob Martin says the ideal number of parameters is 0 and that 3 is stretching it.
32 parameters is a massive code smell. It means the class has way too many responsibilities and needs to be refactored. Even applying a parameter object refactoring sounds to me like it would hide a bad design rather than solve the issue.
From Clean Code Tip of the Week #10:
Functions should have a small number of arguments. No argument is best, followed by one, two, and three. More than three is very questionable and should be avoided with prejudice.
Hmmm 32 parameters is way too much.
There are as many rules as people i guess. However, common sense dictates that more than 6 becomes unwieldy.
When you have so many parameters it's always better to pass an object as a single parameter and have the parameters as properties, at least is easier to read.
C# doesn't limit maximum number of parameters, AFAIK.
But IL does: 0x1FFFFFFF.
Of course, this post isn't a guide to write methods with huge amount of parameters.
I believe that a common feeling from the developer community is about 5 or 6 parameters maximum. The times that I've seen methods like yours, it is someone doing something like "SaveCustomer" and pass every field instead of passing a customer object.
There is no silver bullet answer for this. Everything depends on you and your dev group.
The quantity of parameters may arrive also on numbers like 32, even if this leads to think about poor design, but this is kind of things that may happen to meet during career.
General agreement on this is
use as less as pssible
use overloaded functions, to slice parameters between different functions
func A(a,b)
{
A(a,b,c);
}
can use params keyword to pass arbitrary information in array, like object[]
can use Key-value stores where you can hold a lot of information and recover it
In general they say that the code-line has not to be long as much then constrain you to scroll horizontally in your editor, even if this is not strictly related to question subject, but may lead to some ideas on it.
Hope this helps.
You could take another approach by creating an object that is passed in as single parameter?
I have never head of a rule of thumb for parameters, but common sense and practicality usually prevails.
While I suspect the question will get closed as argumentative, 32 is definitely too many.
One option is to look at the builder patter, which will at least make the task more readable.
I think nowadays the most important thing would be readability for humans as opposed to performance. I doubt that a similar performance behaviour exists in .NET anyway, but even if it did, code that is correct is infinitely more useful than code that performs slightly quicker but that does the wrong thing. By keeping it easy to understand, you increase the chances of the code being correct.
A handful of parameters - rarely beyond 5 in my experience - is best most of the time. You could consider refactoring code that requires more than this by providing the parameters in the form of properties on a class which the method is subsequently called on.
I think it is pleasant to have zero up to five parameters per method.
But this depends on varying things, like coding style and class design.
Look at the .NET Framework, you will see often this:
A class with methods that almost have less or no parameters, but uses few properties to control the behavior of the class (instead of 30 parameters).
A class with huge set of methods with less or no paramters and with almost no properties. e.g. BinaryReader.
Keep your public API so simple as possible. Less parameters helps other developers to use your class without to learn to much about 'how it works'. Makes code more legible.
Valentin you have right feeling, 32 parameters mean only one - something going totally wrong.
From my past experience in C++, I saw only one "parameters" leader:
It was Win32 APi CreateWindow with 11 params.
You should never ever use such huge quantity of parameters.
From other hand, if you interested in question from theoretical point (probably it can be asked at interview) - How many parameters allowed for method?
So, here as was mention above C# method can have no more then 0x1FFFFFFF parameters (IL limitation).
You can use params[] array to set up such huge quantity.
And why exactly such limit?
Because, if you convert this value to bytes and multiple by reference size (4 bytes) you will receive exactly 2 GB.
There are 2 GB limitation on all objects in .NET and you are never allowed to create a single object that exceeds 2 GB.
As far as I know there isn't any hard and fast rule for how many parameters you should have. It depends entirely on what you are doing.
However for most applications, 32 parameters sounds like a bit too much. It might indicate a bad design. There might be a way to simplify things if you look closely.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Is it pretty common to declare it near the bottom in C# code?
I seen few example where its done that way.
There are tools like Resharper which help you organize your source code, does it have an option to specify where it should create regions for me?
This is a stylistic discussion because with the majority of compilers the placement at the top or bottom (of a class file) doesn't affect the results. Historically a lot of people do it at the top, but I like to leave them at the bottom.
Why?
Because once I've declared that member variable, I don't need to see it anymore - it shows up in my intellisense, so I don't need it in my face. When you open a file, you see the top - I want to see my code straight away, not a bunch of variable declarations. This is especially relevant because variable definitions are not a natively collapsible region in the VS editor, so if they're at the top you are forced to scroll past them. If I need to jump to it then Visual Studio's F12 or just a Ctrl+End will take me there.
This is a style that some may find hard to deal with initially, but it does grow on you quite quickly. This is a particularly good approach on files that are more mature. You will also find that if you are using a plugin like ReSharper it is smart enough to put generated declarations with all the others - which means if you have them at the bottom that's where ReSharper will put it. Of course this can get messy if you have multiple classes in a file, but if you do then variable definition placement is the least of your stylistic issues.
Edit:
at the risk of drifting off topic, a comment on using a #region block instead: I use regions all the time, I love them because they help me collapse code down out of the way. However using them requires discipline as it is easy for non-related code to make its way inside the region. How many times have you looked for code only to find it buried in a #region where it didn't belong?
I declare them at top. Try out StyleCop... I think it will give you a recommendation on that, and a million other style issues... its kinda cool... And you can disable rules you disagree with
My (late) five cents on this topic:
I like stateless programming. Before auto-implemented properties existed, the number of private fields in a class was a rough measure of its statefulness. That's why I preferred to keep them at the top to have a quick impression. For the same reason, now I like to keep auto properties grouped together at the top.
AFAIK there is no common convention. Some people prefer grouping the things logically: fields and the methods/properties operating with them go together. Others prefer putting public things on the top and private at the bottom.
What is really important, is that you use the style consistent with your team's style. Or, if there is no team style yet, try to convince the team to adhere to one (you'll need to persuade them that your style is better than no style).
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Since forever, strongly-typed objects have been a foundation of object-oriented programming. Fast-forward to 5 minutes ago, when working with the Entity Framework and MVC3, I was forced to add this to my Web.config:
<connectionStrings>
<add name="_MY_EXACT_CLASS_NAME_DbContext" connectionString="Data Source=blahblah.../>
</connectionStrings>
Great, My entire application depends on an arbitrarily-chosen name in an XML attribute. Is this really what modern programming looks like? Misspelling a class name is a serious offense, one the compiler leads us directly into fixing, but in this case, I'll just get a runtime exception message. If Mr. aforementioned exception message in a good mood, he'll point me toward Mordor, and I'll trudge off toward another Mount Doom of wasted debugging hours to destroy the invisible One-Typo-To-Rule-Them-All.
The same goes for Controllers:
routes.MapRoute("BE_CAREFUL","{controller}/{action}/{id}",
new { controller = "ONE_FALSE_MOVE_AND",
action = "BUT_I_SWEAR_IT_SAID_BUILD_SUCCEEDED" }
);
It seems like things come and go in waves. Strongly-typed objects had their day in the sun, and now we're all girl-next-door over the anonymous "var". I'll admit, being coy about your type stirs up a lot of sexy scenarios - especially knowing you don't have to do any setup work - but here's The Actual Question:
How do the forefathers of object-oriented programming feel about our "advancement" of their art by adding a bunch of wishy-washy, do-sorta-whatever anonymous constructs while at the same time creating fragile dependencies on naming conventions?
For all we know, MVC4 might suddenly require that all names be preceded by exactly 4.7 spaces followed by lolcat ASCII art. Why? Because yes, that's why. Take a moment and marvel at the fact that you just witnessed the birth of a naming convention. Obviously, this is seriously solid foundational material for a flagship framework.
So, if there's one thing I want my entire codebase to both functionally and philosophically depend on, there's nothing more mission-critical to the mathematic logic of programming than..... Microsoft's® English-Language Naming Conventions!
</sarcasm>
</griping>
<!-- resume enjoying all of MVC's amazing features, after eating any humble pie served up in the comments -->
My entire application depends on an arbitrarily-chosen name in an XML attribute.
This is called "coding by convention" or "convention over configuration" ... you pick a few things that need configuration, and then everything else just "falls into place". Like using razor and having _layout.cshtml in /views/shared. Or like using razor and having mySpecialController with ActionResult Index and /views/mySpecial/Index.cshtml ... those are just a way of letting the convention work for you.
Since forever, strongly-typed objects have been a foundation of object-oriented programming.
Strongly-typed objects had their day in the sun, and now we're all girl-next-door over the anonymous "var".
var variables are just a shorthand to make things slightly more readable, the compiler still strongly and statically types things at compile time. Consider the difference here:
foreach (var c in Customers) { /* do stuff */ }
foreach (CustomerDataItem customerDataItem in Customers) { /* do stuff */ }
As you can see, the first one says "get a item c from Customers" and the second one says the same thing but good lord man I've already written two more lines of code while you're still typing the long one. Granted, with ReSharper that advantage disappears, however ...
For all we know, MVC4 might suddenly require that all names be preceded by exactly 4.7 spaces followed by lolcat ASCII art. Why? Because yes, that's why.
har.
How do the forefathers of object-oriented programming feel about our "advancement" of their art by adding a bunch of wishy-washy, do-sorta-whatever anonymous constructs while at the same time creating fragile dependencies on naming conventions?
Ok, so this was mostly just frustration, but I'll bite. The guys that started wanted simpler code (BASIC, COBOL look up what those mean) and so they want things to be easier and more math-y. That's where things are moving (LINQ is set math, and higher order calculus; also see F# and Python)
So they would LOVE what we're doing now. Getting away from procedural code (algebra) and moving into set-oriented logic (adv calculus). Also see Event Handlers ;-)
So .. having said all that: I've been in your shoes. I've asked those questions. I've studied at the feet of masters. I love where the languages are going.
In your next life, I want you to learn node.js. I want you to learn async evented processing, and I want you to understand how things don't rely on ANSI-C anymore. We've made a lot of progress in this industry, and things are looking up. Things are looking up every day. I love where we are, and I think it's the right thing for our industry.
Cheers, and HTH.
My answer: "because of the advancements in automated testing".
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Which of the following three options would you choose for a property name in C#, and why?
YearToDateWages
YTDWages
YtdWages
I would go with 1. I prefer not to abbreviate anything, unless it's a super-common acronym that would be ridiculous to spell out. Something like "HyperTextTransferProtocolRequest" would be ridiculous to spell out, so it's safe to abbreviate that as "HttpRequest." It's a little subjective, but when in doubt, I tend to not abbreviate.
If you decide to go with 2 or 3, I'd probably vote for 3, based on the recommendations from the "Framework Design Guidelines." It basically says that for acronyms that are 3 or more letters long, you should capitalize the first letter and lower-case the rest. It's a little ambiguous on 2-letter acronyms... Some people prefer to capitalize all letters like "ID" and some prefer to go with "Id". The guideline is to actually capitalize all letters of a 2-letter acronym, but that kind of contradicts with the guideline for 3+ letter acronyms, so people do it both ways.
I would use YearToDateWages, because without that being in the list I wouldn't know what you were talking about.
See also the general naming guidelines on MSDN:
In general, you should not use abbreviations or acronyms. These make your names less readable. Similarly, it is difficult to know when it is safe to assume that an acronym is widely recognized.
For capitalization rules for abbreviations, see Capitalization Conventions.
Do not use abbreviations or contractions as parts of identifier names.
For example, use OnButtonClick rather than OnBtnClick.
Do not use any acronyms that are not widely accepted, and then only when necessary.
Emphasis in original.
bool ShouldIUseAbbreviate(string abbreviate_)
{
foreach (var peer in myPeers)
{
if (!peer.CanGetTheMeaningWithinOneSecond(abbreviate_))
{
return false;
}
}
return true;
}
I think the first one is best because it is self descriptive.
Microsoft suggested naming convention rule out #2
anything with > 2 acronym letters should be Xxx not XXX
but 2 should be XX
I like less typing so I would go with YtdWages
It depends.
If you are making a library that will see external use, the .NET Framework Design Guidelines say that #1 is preferred.
If it's an internal application/library, then I recommend using the format that is consistent with your teams development standard.
I would opt for the full name rather than one featuring an acronym. It is more descriptive, and while "YTD" may be obvious to some, it might not be to everyone. YearToDate is not excessively long and the meaning is clear.
Is there a reason why you would not use the first one?
It is not only for others; if you have to change something in your own code 2 years later, good, descriptive names will help you.
The .Net framework seems to follow mostly #1. So I would stick with it. Abbreviations should be avoided except where extremely commonly known at the class level. Of course for local(function) variables this is much less strict and I would say that abbreviations and short names are much more appropriate so as to make the code smaller and more concise.
Examples of good abbreviations are XML and HTTP. Who is seriously going to write
string x=myobject.HyperTextMarkupLanguageOutput;
I vote for number 1 as well.
There will be very few times when you do NOT want a descriptive name.
Visual Studio will assist you with the long names.
Semi off topic note:
If you cant find a suitable name... perhaps the planned usage is not that clear after all ;)
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
Since C# is strongly typed, do we really need to prefix variables anymore?
e.g.
iUserAge
iCounter
strUsername
I used to prefix in the past, but going forward I don't see any benefit.
Are variable prefixes ( Hungarian ) really necessary anymore?
NO!
In fact, Microsoft's own style guidelines (where the practice originated) now recommend against it. In particular, see the section on General Naming Conventions, which includes the following text (in bold type, no less):
Do not use Hungarian notation.
Of course, these guidelines are not binding or mandatory outside of Microsoft. However, this is the published recommendation of the platform vendor, and it goes beyond merely removing the positive recommendation from any prior guide, to instead a strongly-worded and emphasized negative recommendation today.
In other words, don't use them anymore.
The only places I see fit to bend the standards and prefix variables:
control names: txtWhatever - and I see I'm not the only one. The nice thing is that you can come up with stuff like lblName next to txtName, and you don't need to go into the NameLabel/NameTextBox direction.
class member variables: _whatever. I've tried both m_ and no prefix at all and ended up with simple underscore. m_ is more difficult to type and having no prefix becomes confusing sometimes (especially during maintenance, I know all of you know their code by heart while writing it)
I didn't find any consistent situation where prefixing a variable with its type would make the code more readable, though.
EDIT: I did read the Microsoft guidelines. However I consider that coding styles are allowed to evolve and/or be "bent", where appropriate. As I mentioned above, I found using underscore prefix useful by trial and error, and is certainly better than using this.whatever everywhere in the code.
Supporting the "evolving" theory - back in .NET 1.x when Microsoft released coding guidelines, they advised using Camel casing for everything, even constants. I see now they've changed and advise using Pascal case for constant or public readonly fields.
Furthermore, even .NET Framework class library is currently full of m_ and _ and s_ (try browsing the implementation with the Reflector). So after all, it's up to the developer, as long as consistency is preserved across your project.
If Hungarian means "prefix with a type abbreviation" such as uCount or pchzName, then I would say this practice is bad and thankfully seems to be fading from common use.
However, I do still think that prefixes are very useful for scope. At my studio we use this convention for prefixing variables :
i_ // input-only function parameter (most are these)
o_ // output-only function parameter (so a non-const & or * type)
io_ // bidirectional func param
_ // private member var (c#)
m_ // private member var (c++)
s_ // static member var (c++)
g_ // global (rare, typically a singleton accessor macro)
I've found this to be very useful. The func param prefixes in particular are useful. Way down inside a function you can always tell where that var came from at a glance. And typically we will copy the var to another when we want to modify it or change its meaning.
So in short: prefixes for types are unnecessary with modern tools. The IDE takes care of identifying and checking that stuff for you. But scope-based prefixes are very useful for readability and clarity.
There are also fun side benefits like with Intellisense. You can type i_ ctrl-space and get all the input params to the func to choose from. Or g_ ctrl-space to get all your singletons. It's a time-saver.
Nope. Did we ever need to?
Hungarian notation is ugly. The only exception is with interfaces, where most people think it's acceptable.
Linus sums it up well:
"Encoding the type of a function into the name (so-called Hungarian notation) is brain damaged - the compiler knows the types anyway and can check those, and it only confuses the programmer"
No. Hungarian Notation just adds unnecessary noise to code and is redundant with compiler type checking.
Yes, if Hungarian notation were used as it was originally meant, instead of as implemented by Microsoft. Much like the example above, which shows text boxes and corresponding labels as lblWhatever, txtWhatever. Use it to define the use of the variable, not the type. It can provide information to know that your number is moneyTotal, which tells me more than just the data type.
But, as commonly used? No.
Prefixes are a leftover from the VB (and older!) days when Hungarian Notation was king. That is no longer the case, though the C# community does mandate things like using a prefix of Capital I for interfaces (e.g. ILoadable).
The current Microsoft Guidelines are here.
Hungarian notation is no longer needed to identify data types like in your string example, but it still can be useful for identifying characteristics of variables in other ways. Here's a good article that talks about useful ways of using the Hungarian notation: http://www.joelonsoftware.com/articles/Wrong.html
Here's an excerpt
"In Simonyi’s version of Hungarian notation, every variable was prefixed with a lower case tag that indicated the kind of thing that the variable contained.
For example, if the variable name is rwCol, rw is the prefix.
I’m using the word kind on purpose, there, because Simonyi mistakenly used the word type in his paper, and generations of programmers misunderstood what he meant."
He also uses an example of identifying strings prefixed with an 's' or a 'u' to identify if they are secure to print out or not, so that a statement like print(uSomeString); can easily be identified as wrong.
Most of the arguments I see against Hungarian notation mention that modern editors and IDEs are perfectly capable of giving you all the information you need to know about every identifier. Fair enough.
But what about printed code? Don't you carry out code reviews or walkthroughs on paper? Don't you use printed code for training purposes? Don't you use code snippets for online help? Hungarian notation is extremely valuable in these occasions.
I keep using (some sort of) Hungarian notation in all my code. I find its absence ugly and lacking in information.
I personally don't anymore, however you will still people argue to prefix for scope.
I go with Microsoft and use their Capitalization Styles for all naming conventions. The entire "Design Guidelines for Class Library Developers" section, which that link is a part of, is pure gold, in my opinion.
Additionally, I love the "Framework Design Guidelines" book from Addison Wesley. It covers all of these guidelines with annotations from Microsoft team members on to why they recommend what they are proposing and how it is adopted within the organization.
Well, to counter, I'd say - it depends. I'm personally against them, but it comes down to your team. Each team should be responsible for developing their own set of guidelines. Hopefully that doesn't include so-called Hungarian Notation, but it really should be a team decision. You might find cases where you want to break with the style guidelines.
What makes me curious about this question is the fact that the languages (C then C++) where prefixing (i.e., Hungarian notation) was introduced were also strongly-typed. For all I know, it was done with Pascal's use at Microsoft as well. And it would seem that it was also used with Mesa, a strongly-typed language that the Hungarian may have had some familiarity with [;<).
That being the case, it is fair to get beneath the question and consider (1) what problem was prefixing used to help solve and (2) how has that problem gone away?
I know that's not exactly an answer, but it might be more useful than the blanket objections to use of prefixes as outmoded or wrong-headed.
Even though the compiler can quickly and easily check the type of a variable, humans are unable to do so while skimming a piece of source code.
Therefore some people (like me) prefer to make variable names a tad more verbose, making them quickly recognizable to be global or class variables, string or int, etc.
It might not help the compiler, but when reading a foreign piece of code, it surely saves you having to look up each variable manually...
Definitely not. As a general rule, I've come to believe that it's just noise. If you're an indepedent consultant or your company doesn't have a comprehensive style guide, IDesign has a great guide. Just look on the right hand side of the page and you can D/L the latest iteration of their C# Coding Standard document.
Steve
I only use it in my database (PostgreSQL)
t_ for table name
v_ for view name
i_ for index name
trig_ for trigger
sp_ for stored procedure name
p_ for parameter
v_ for variable
c_ for cursor
r_ for record
Hungarian notation was never meant to be used to show what data type the variable was. It was misunderstood to suggest that "str" or "i" be used to implicitly define the type. It was meant to only show the "kind" of variable, not the "type."
So to answer the question, it shouldn't be used now nor should it have ever been used in the past.
I know it has been linked, but scroll to the bottom of Joel's article for more info - http://www.joelonsoftware.com/articles/Wrong.html where he talks about where Hungarian
For a general overview of good conventions see here:
http://msdn.microsoft.com/en-us/library/ms229002.aspx
There is a book about that in which they explain the reasons behind each of that conventions. Pretty interesting read.
I always prefix instance member variables with m__ and static member variables with s_. I've come across variable articles from MS people who recommend/discourage the approach.
I'm also pretty sure I've come across the m_ prefix when looking through the standard .NET libraries using Reflector...
No, we don't need them. I used to follow this when back in the days, we were forced to follow that kind of a coding standard.
Also with Intellisense, Code Definition Window and Refactoring tools built into VS and other third party plugins like CodeRush express and Refactor Pro, it's easier to work with code without it.
Inside the code and when working with data types I see no reason for the use of Hungarian notation.
But when I'm working with a series of user interface control, be that they are textboxes, dropdown lists, grids or what not, I like to have my intellisense work for me. So to accomplish that, I usually make the id of the control with a prefix of "uxSomeControlName". This way, when I'm looking for that textbox to grab it's text value, all I have to do is type "ux" and all of the user interface ID's are displayed. No need to search for txt, ddl, grd, or anything else.
Now is this correct, if you read the above, no. But I don't want to sit hear and try to remember a dozen or more control names when I just have to know two letters.
Like I said, this is only when working on the front end.
I use it all the time but that could because I use VBA with Access and Excel.
For me CountAll is a name intCountAll is a name with this difference that it additionially describes the name (never intended for machines just for humans) like sintCountAll tells me its static pintCountAll private and gintCountAll global so for the purpose I use it; it is very usefull.
control names is a time safer like instead of ControlName I have lblControlName, txtControlName, cboControlName, lstControlName etc so when I use VBA I just type lst and I have all the names I need so I don't have to remember what is the exact name which saves me a lot of time but again this is mainly VBA in Access and Excel.
Regards
Emil
The only prefix I would consider for C# is a _ for member variables such as
public class Test
{
private int _id;
}
I would say that in most languages these days that have a limited set of types - in particular no concept of unsigned types - then a well-named variable shouldn't need the prefix.
In languages that have signed and unsigned types, or a slew of similar types (e.g. short, int, long or Int8, Int16, In32), then prefixes are useful, despite what anybody else has or will say (and they will, you know it).
The compiler will, at best, give a warning when you try and mix integral types of different signs in expressions, and this could easily be missed if, for example, you configure your IDE to only show errors (not warnings) in a build in the final summary (as you can do with Visual Studio). Mixing signs in arithmetic can seriously ruin your day, so save you or your successor a headache and give them a clue. Remember - you're not the only one who will ever look at the code.
A solution to a problem that doesn't exist.
While many programmers today are abandoning it, I would still use it in certain cases. Here are some of them;
If you are maintaining code that
already uses it, then I would keep
using it.
When your company style guidelines
still require or even suggest it.
When your documentation has a simple
alphanumerically sorted list of
variables, it helps group like types.
I sometimes use a kind of prefix where pName is a parameter passed into my function (notice I don't prefix the type), oName is local to my current method, mName is a member to the class I'm in and cName is a constant or static readonly member.
Personally I find it helps.
The short answer is NO. But...
I see the point of getting away from Hungarian notation, the standards in our shop forbid it, too, but I still find it useful in my one-off or little utility projects for one reason and one reason only: when I am coding to a large number of controls in a web or win form, using HN makes it easy to use Intellisense make sure I catch every single control while coding.
If I have a five checkboxes and their names all start with chk then typing chk gives me the list of every one of them and I can easily pick which one I'm working on that moment.
Also, sometimes I find myself wondering "what the heck was that checkbox named again?" And I have to break off and look in the .ASPX page again.
One way I have compromised is to begin with HN, and then once I have gotten the main code in a win or web form complete, my last step is to do global renames for the HN-named controls. This has actually worked well for me. YMMV, of course.
No, if your methods are so long that you cant read the definition at the same time as the use, or the name doesnt imply the type then you have more serious design issues than just naming.
However, i INSIST that you do prefix controls with their type, such as txtName.