I am in a new team. I am shocked by their coding guidelines.
Example:
strName
iCount
structRectangle
listCustomers
retVal (for the return value... that is really biting me... how someone can do this)
They demand to write the datatype before the variable with the argument that this way the developer knows everytime what datatype the variable is without scrolling up to the declaration.
Well that is true, but my argument would be then a method should not be longer than 30 lines (else put code in another method) which fits into a common 24" screen...
But I am not totally convinced because there are things like Action<T>, Dynamic, Func<T> in .NET. which force me too to go the same way and do "actionCustomers" for a delegate holding a method gettings a list of customers.
What advice can you give me as an alternative to e.g. "actionCustomers" which should render the argument of the team useless?
I would suggest that you adopt the coding style of the team you are coding with. They have adopted their style to deal with their own systemic problems. Unless you are in a position to judge their code (which it seems you are not) or you can appeal to a higher authority on code style (seems unlikely from your post) then, if you want to keep your job and demonstrate that you're a team player, you need to conform to the rules you've been given.
Why is datatype in variables bad coding style?
It's not. A relatively ancient form of it called Systems Hungarian Notation that actually encoded the type has received a lot of criticism for a lot of reasons, including redundancy, inconsistency, and poor readability. But that's not what you're dealing with. I sometimes find it helpful to include datatypes in my object names when I haven't fully decided on which container I'm going to use (list, no, set, no, dict... and usually in that order.)
This coding style is very useful when you are not using an IDE.
I often open old code files with Notepad++ (just to read it and convert to newer code, no need to open huge project to read one single file) and without this coding style, every time I see a variable, I have to search for its name inside the document just to find out its type. And that hurt my time schedule A LOT.
Long story short: you may not like the old school methods but they existed because people needed them. You will never know if one day you wish for it.
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.
Linus Thorvalds, Linux Kernel Coding Styles
I really love that quote.
I am developing a framework, and some of the objects have reaaally long names. I don't really like this, but I don't like acronyms either. I am trying to come up with a shorter name for "EventModelSocket", basically a wrapper around the .Net socket class that implements various events, and methods to send files, objects, etc. Some of the objects have really long names due to this, such as "EventModelSocketObjectReceivedEventArgs" for example.
I've tried everything from a thesaurus, to a dictionary to sitting here for hours thinking.
When you come upon situations like this, what is the best way to name something?
Push some of it into the namespace.
For example:
EventModelSocketObjectReceivedEventArgs
becomes
EventModel.Sockets.ReceivedEventArgs
Well, are the long names hurting something?
(edit) two other thoughts:
use var in C# 3.0 - that'll save half the width
if you are using the type multiple times in a file, consider a type alias if it is annoying you:
using Fred = Namespace.VeryLongNameThatIsBeingAnnoying;
I would just suggest using the most concise naming that describes the object.
If EventModelSocketObjectReceivedEventArgs does that, move on.
My 2 cents.
Years ago when I was in a programming class, the prof quoted the statistic that a piece of code is typically read 600 times for each single time it got modified. Nowadays, I would assume that this is no longer true, particulary in TDD environments where there's lots of refactoring going on. Nevertheless, I think a given piece of code is still read many more times than it gets written. Therefore, I think the maxim that we should write for readability is still valid. The full form of a word in a name is more readable, since the brain doesn't have to do the conversion. Comprehension is faster and more accurate.
The tools we have today make this so easy with autocompletion and the like. Because of this, I use full words in variable names now, and I think it's a good way to go.
If you need to go through that much effort to find an alternative name, you already have the correct name. Object/method/property names should be self documenting. If they do not describe their exact purpose they are misnamed. There is nothing wrong with long names if they give the most clear understanding of the purpose of that object.
In this age of intellisense and large monitors there really is no excuse to not be as descriptive as possible in naming.
Don't remove the vowels or something crazy like that.
I'm with the "stick with the long name" people.
One thought is that if the names are that awkward, maybe some deeper rethinking of the system is needed.
I for one use the long name. With intellisense typing out the name isn't that important, unless you are using a 15 inch monitor.
If I had to reduce the name I might go with EvtMdlSck just make the work shorter but still understood. Even though that is not my preference.
Some criticisms on your naming...
Why DOES your component have the word "model" in its name - isnt that a bit redundant.
Since your component seems to be a messaging hub of some sort why not include
Message in its name. What about MessageSender.
To solve your problem I would create an interface and given it a generic name like
MessageSender and an implementation which is where you include the technology within the name like RandomFailingSocketMessageSender.
If one wishes to get a good example of this take a look at the Java or .Net libraries..
from Java.
interface - class/implementations...
Map - HashMap, LinkedHashMap.
List - LinkedList
Details regarding the technology or framework used eg words like "Socket" or perhaps to use a contrived example "MQSeries" shouldnt be part of the interface name at all.
MessageSender seems to IMHO sum up the purpose of your component. It seems strange that your thing which sends "files" and "events" doesnt include the those two descriptive words. The stuff your using in your naming is superfluous and IMHO doesnt match your description of the component.
In general I believe in classnames that accurately describe their function, and that's it's OK to have long names. If you think the names are really getting long, what I would suggest is finding a concept that is well-known to your programming team and abbreviating that. So if "Event Model Sockets" are a concept that everybody knows about, then abbreviate them to EMS. If you've got a package that is entirely about Event Model Sockets then abbreviate them to EMS in all the classes internal to that package. They key here is to make sure the name is in full for anyone who might not be familiar with the concept and abbreviated for anyone who is.
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.
Over the years as I have gone through school and been working in the industry I have often asked people for advice on commenting. Sadly, as we all know, commenting with many developers is something that is taken as a side note and not much else. With that said I usually get a fairly general answer. Really this does not help much to see what will really help as time goes on.
So, what do you think is the best way to structure C#, with Visual Studio, commenting?
At the very least, I would comment all parts of your public API, using a triple-slash XML comment block. This will make it easy to auto-generate documentation if and when the time comes.
Beyond that, I would comment any particular algorithms or pieces of code which are going to be hard to decipher in six months time. This 'selfish' approach to commenting (i.e. assume you'll have to maintain this code later) often leads to the best balance of ample documentation without overkill.
I try to follow some basic guidelines when writing comments.
Comments should be simple
Comments should provide clarity
Write documentation before you write implementation
Document why you're doing something, not what you're doing.
Use built-in (XML-style) comments for interfaces, methods, properties, and classes.
Provide a summary at the top of every file (e.g., Something.cs) with the file name, description, development history, and copyright information
Add comments for bug fixes (with bug number, if appropriate)
Make use of helpful annotations like //TODO //BUG and //BUGFIX
Don't comment out code unless you plan to use it
Add comments above the line(s) of code they apply to, not to the end of the line
Try to limit comments to a single line
Use // instead of /* */ for multi-line comments
Be clear--do not use "foo," "bar," etc.
Follow casing rules where appropriate (i.e., camelCasing and PascalCasing)
"Plenty and often"
--Bilbo, The Hobbit.
More seriously, comment things that are not obvious, and tell the reader what the goal of the code is, and perhaps why you chose it.
That's not going to change based on language.
Personally I use a combination of triple slash, SandCastle XML comments and inline comments for more complicated sections. Comment often but keep it concise, nobody needs to read reams of fluff before then can figure out what something does :-)