Why shouldn't I prefix my fields?

I’ve never been a fan of Hungarian notation, I always considered it useless if you are not programming at the lowest level, but in every C ++ project I’ve worked on some Hungarian notation policy, and use some with it. " non-really-hungarian "prefixes like m_ for fields, s_ for statics, g_ for globals, etc.

Soon, I realized how useless it was in C # and gradually began to drop all my old habits ... but the thing is "m_". I still use the m_ prefix in private fields because it is really very useful for me to distinguish between parameters, locales and fields.

the naming convention for the margin page on MSDN says I shouldn't, but it doesn't say why (for example, rationalize their recipes as a rule).

Are there any reasons why I shouldn't or is it just a matter of style. If this is the latter, are prefixes generally considered bad style, and can I expect negative reactions from other codebased people?

+49
c # naming-conventions field hungarian-notation
Mar 18 '09 at 18:30
source share
25 answers

I like the underbar prefix for member fields. Basically, I like it, because in this way all the fields of my member are displayed in alphabetical order before my methods in the wizard panel at the top of the screen.

Wizardbar

+52
Mar 18 '09 at 18:51
source share

When you need:

  • When your coding guidelines for a project say you should

If you must not:

  • When your coding guidelines for a project say you shouldn't

If you don’t have any instructions yet, you can choose what you or your team want and feel most comfortable. Personally, when coding C ++, I try to use m_ for members, but that helps. When coding in other languages, especially those that do not have true classes (for example, Javascript, Lua), I do not.

In short, I do not believe that there is a “right” and a “wrong” way.

+38
Mar 18 '09 at 18:35
source share

The automatically implemented property function in C # 3.0 creates less need for this convention anyway. Instead of writing

string m_name; public string Name { get { return m_name; } } 

or

 string _Name; public string Name { get { return _Name; } } 

(or any other agreement), you can write

 public string Name { get; private set; } 

Since you no longer need an explicit backup of the vault, you no longer need to provide a name for it; thereby avoiding all this discussion.

Obviously, this argument does not apply when you really need an explicit support repository, for example, to perform validation.

+21
18 Mar '09 at 18:38
source share

As mentioned by some of them, the MS recommendations say:

Do not use a prefix for field names. For example, do not use g_ or s_ to distinguish between static and non-static fields.

I agree with it. prefixes make your code look like ugly and unnecessary space with inconsequential characters. Having said this, they often use fields to return properties, where both the field and the property have the same name (with a private field being the case of a camel, and the property is pascal). In VB, this does not work, since VB is not case sensitive. In this case, I recommend using a single prefix. No more no less. He just looks cleaner, IMHO.

+11
Mar 18 '09 at 18:53
source share

I experimented with m_, s_, just _ and without a prefix. I decided to use only _ for all static and instance variables. I do not consider it important to distinguish between static variables and instance variables. Theoretically, this sounds good; in practice, this does not create a problem.

The employee once made a convincing argument to eliminate all the prefixes, we tried it in one project, and it worked better than I expected. I transferred it to my next project and became annoyed that it was "interfering" with Intellisense. If you have the following situation

 int foo; public int Foo { get { return foo; } } 

Starting with type foo, both an instance variable and a property will be offered. The variable prefix with an underline eliminates the annoying double sentence, so I switched to using only _.

+11
Mar 18 '09 at 19:24
source share

I try to follow the recommendations of MSDN.NET . They include naming principles .

Obviously, they are secondary to your projects.

+10
Mar 18 '09 at 18:37
source share

I prefer to mark property support fields (although, as already mentioned, .NET 3.0+ reduces the need due to automatic properties) with underlining, but not with "m". For one, he puts them at the top of the InteliSense list when I use them.

I admit that I need to deal with MSDN recommendations, these days everything can change.

+10
Mar 18 '09 at 18:48
source share

With tools like resharper, there really is no reason for prefixes. Also, if you write short methods, you should be able to quickly tell where var comes from. Finally, I think I would not see the need to tell the difference between statics or not, because again the resharper is going to the red line if you are trying to do something that you cannot. Even without resharper, you are probably saved by the compiler.

+9
Mar 18 '09 at 18:50
source share

I always have prefix member variables with m_ and static variables with s _ for the same reasons as you. Some people have prefix variable variables with underscores, but I always found this a bit strange (but this is just a personal preference).

Most of the people I work with use the m_ / s_ prefix. I really don't think this is too important for you if you agree.

+6
Mar 18 '09 at 18:36
source share

I never use them. He encourages sloppy coding. MSDN coding guides where it is located.

+5
Mar 18 '09 at 18:41
source share

Here are a few reasons to use _ (rather than m _).

(1) Many of the BCL guys do this despite the MS naming guide. (Check out their blog .) These guys are writing a framework, so they have good habits that are worth copying. Some of the most useful MSDN code examples are written by them, and therefore use the underscore convention. This is the de facto industry standard.

(2) The only underline is a noticeable but unobtrusive way to eliminate the ambiguity of the method and class level variables by simply reading the source. This helps people understand the new (or old) code when looking while reading. Yes, you can hover over it in the IDE, but we should not be forced. You can read it in a text editor or dare to say it on paper.

(3) Some say that you do not need any prefix, since the methods will be short, and later, if necessary, you can change the field to an automatically implemented property. But in the real world there are methods as long as they should be, and there are important differences between fields and properties (e.g. serialization and initialization).

Footnote: “m” for the member in m_ is redundant in our use here, but it was lower case because one of the ideas in many of these old naming conventions was that type names start with an uppercase and instance name, started with lowercase. This does not apply to .NET, so it is doubly redundant. In addition, Hungarian notation was sometimes useful for older C compilers (for example, for integers or pointers and arithmetic), but even in C ++ its usefulness decreased when working with classes.

+4
May 03 '10 at 23:37
source share

I'm used to the fact that private properties got a small lower part of f.ex "string _name". public received "Name". and the input variables in the methods received the small letter "void MyMethod (string name)".

if you get a static const is often spelled in capital letters. static const MYCONST = "hmpf" .

+3
Mar 18 '09 at 18:47
source share

There is one important difference between C ++ and C #: tool support. When you follow the established rules (or common options), you will get a deep level of support for a tool that C ++ never had. Following standards, the tools allow you to perform deeper refactoring / renaming operations than you otherwise might have. Reshir does this. Therefore, adhere to one of the established standards.

+3
Mar 18 '09 at 18:47
source share

As @John Kraft notes, there is no “right” answer. MattJ is the closest - you should always follow the recommendations of your corporate identity. When in Rome and all that.

As for my personal opinion, since he is called here, I vote for you to completely drop m_ .

I believe the best style is one where all PascalCased members, regardless of visibility (which even means private members), and all camelCased arguments. I do not violate this style.

I can understand the desire to prefix the field of the property properties store; you have to distinguish between field and property, right? I agree, you must. But use post-fix.

Instead of m_MyProperty (or even _MyProperty , which I saw and even raised once), use MyPropertyValue . This is easier to read and understand, and more importantly, it is close to your original intellisense property name.

Ultimately, the reason I prefer postfix. If I want to access MyPropertyValue using intellisense, you (usually) type " My <down-arrow> <tab> ", since by that time you are close enough that only MyProperty and MyPropertyValue . If you want to access m_MyProperty using intellisense, you will need to enter " m_My <tab> ".

This is about the keypress mechanism, in my opinion.

+3
Mar 18 '09 at 19:08
source share

I never do this, and the reason is that I [try] to keep my methods short. If I can see the whole method on the screen, I can see the parameters, I can see the local residents, and therefore I can say what belongs to the class and what is the parameter or local.

I usually call my parameters and local residents using a specific notation, but not always. I am nothing if not contradictory. I rely on my methods being short, and try not to do X, Y, and Z when they should only do X.

Anyway, my two cents.

+3
Mar 18 '09 at 19:09
source share

If I'm not stuck with vi or Emacs for editing code, my IDE takes care of differential member mapping for me, so I rarely use any special conventions. This also applies to prefix interfaces with self or classes with C.

Someone please explain the style of the .NET I-prefix on interfaces. :)

+3
Mar 18 '09 at 20:17
source share

I never use any Hungarian warts when they give me a choice. This is an additional breakdown and does not convey any relevant information. Any good IDE (and I define "good" based on the presence of this function, among other things) will allow you to have different syntax highlighting for static members, instance members, member functions, types, etc. There is no reason to interfere with your code with the information that the IDE can provide. This is because you did not clutter up your code with commented out old code, because your version control system should be responsible for this stuff.

+2
Mar 18 '09 at 18:49
source share

The best way is to agree on a standard with your colleagues and stick to it. It doesn’t have to be the method that works best for everyone, just agreeing on one method is more important than the method you actually agree on.

What we have chosen for our code standard is to use _ as a prefix for member variables. One reason was that he easily discovered local variables in intellisense.

Before we agreed with this standard, I used one more. I did not use the prefix at all and wrote this.memberVariable in the code to show that I am using a member variable.

With a reduction in property in C # 3, I found that I use much less explicit member variables.

+2
Mar 18 '09 at 18:59
source share

I’m sure that they kindle me for it, but so be it.

It was called the Microsoft.NET library guidelines, but in fact it ’s the views of Brad Abrams ( document here ) - there are other views with good reason.

People tend to hold the majority opinion rather than have good compelling reasons for a particular style.

An important point is the assessment of why a particular style is used and why it is preferable to another style - in other words, there is a reason for choosing a style not only because everyone says what needs to be done - think for yourself.

The main reason for abandoning the use of the Hungarian old style was the use of abbreviations that were different for each team and difficult to learn - it is easy to solve without reducing.

As the available development tools change, the style should change to make more sense, but have a good reason for each style element.

Below are my style recommendations with my reasons - I am always looking for ways to improve my style in order to create more reliable and easy-to-maintain code.

Variable Naming Convention

We all have our own view on variable naming conventions. There are many different styles that can help you create easily maintained, high-quality code — any style that supports basic important information about a variable is fine. The criteria for a particular naming convention should be that it helps to create reliable and easy-to-maintain code. The criteria that should not be used are: ugly Microsoft (i.e., Brad Abrams) says don't use this style - Microsoft doesn't always create the most reliable code, just look at the errors in Expression Blend. When reading the code, it is very important that the variable name instantly conveys three essential facts about the variable: its scope, its type and a clear understanding of what it is used for Scope: Microsoft recommends relying entirely on IntelliSense. IntelliSense is awesome; however, just do not hover over each variable to see its scope and type. Assuming the variable is in scope, it cannot cause significant errors. For example, if a reference variable is passed as a parameter, and it changes in the local area, then this change will remain after the method returns, which may be undesirable. If a field or static variable changes in the local scope, but is considered to be a local variable, unexpected behavior may occur. Therefore, it is extremely important to be able to simply look at a variable (without moving the mouse cursor) and instantly recognize its scope.

The following style is suggested to indicate scope; Nevertheless, any style is perfect for those cases where it clearly and sequentially indicates the scope of the variable: variable m_ of the field p_, passed to the method s_ static variable local variable Type: Serious errors can occur if we assume that they work with a specific type when they actually work with another type - again, we just do not hover over a variable to determine its type, we just assume that we know what type it is, and that is how errors are created.

Abbreviations: Abbreviations are evil because they can mean different things to different developers. One developer might think that leading lowercase "s" means a string, while another might think that this is a signed integer. Abbreviations are a sign of lazy coding - take a little time and enter the full name to understand that the developer must support the code. For example, the difference between "str" ​​and "string" is only three characters — much more effort is required to simplify code support.

General and clear abbreviations for embedded data types only are acceptable, but should be standardized within the group.

Self-documenting code: adding a clear description to the variable name allows another developer to read and understand the code easily - make the name so clear that the team leader can read and understand the code without being a developer.

The order of the parts of the variable name: the recommended order is the description of the scope type, because: IntelliSense will group all similar fields and IntelliSense will group all similar types in each region, which makes searching easier - try to find the variable in another way. It is very easy to see and understand the scope, as well as to see and understand the type. This is a fairly common style and easy to understand, it will pass FxCop

Examples: Here are a few examples: m_stringCustomerName p_stringCustomerDatabaseConnectionString intNumberOfCustomerRecords or iNumberOfCustomerRecords or integerNumberOfCustomerRecords These simple rules will greatly enhance the reliability and usability of code maintenance.

One-line operators of the control structure All one-line operators (if, while, for, etc.) should always be enclosed in curly braces, because it is very easy to add a new operator, not realizing that this operator refers to a control structure that will violate the logic code without generating compile-time errors.

Method exception wrapper All methods must be wrapped with an external trap attempt that captures, provides space for recovery, identification, location, registration, and deciding whether to throw or not. This is an unforeseen exception that causes our applications to crash - by wrapping every method that catches all unhandled exceptions, we guarantee the identification and registration of all exceptions, and also prevent our application from crashing. It takes a little more work, but the results are worth it.

Indentation Indentation is not a serious problem; However, four spaces are suggested without the use of tabs. If the code is printed, the first tab of the printer usually has 8 spaces by default. Different developers tend to use different tab sizes. Microsoft code usually has 4 spaces indented, so if someone uses Microsoft code and uses the other 4 spaces, the code will need to be reformatted. Four spaces make it simple and consistent.

+2
Mar 18 '09 at 19:39
source share

The closest to official recommendations is StyleCop , a tool from Microsoft that can automatically analyze source files and detect violations from the recommended style code and can be launched from Visual Studio and / or automated assemblies such as MSBuild.

We use it in our projects, and this helps to make the style and layout of the code more consistent between the developers, although it should be warned that it is quite getting used to!

To answer your question - it does not allow any Hungarian designations and any prefixes such as m_ (in fact, this does not allow the use of underscores at all).

+2
Mar 18 '09 at 20:33
source share

I no longer use this style. It was designed to help you quickly see how variables are used. In new Dev environments, you see this information by hovering over a variable. The need for this is gone if you use these new tools.

+2
Mar 18 '09 at 22:18
source share

There may also be some understanding that can be gleaned from Coding Coding standards ( Sutter, Herb and Alexandrescum Andrei , 2004). Paragraph No. 0 is entitled “Do not sweat small things” (or: know that you do not standardize.). ”

, : " , ... - likeThis _ ..." (, ++).

, , "... , , ..."

+2
19 . '09 14:12
source share

C/++ , . Intellisense "Go to Definition" - , , , . , , C, , , + .

, m_ - - , . , , Intellisense "Go to Definition", . , , .NET , , , .

+2
20 . '09 14:44
source share

, m_ , .

0
18 . '09 19:34
source share

.

  • .
  • .
  • -.

, , /.

0
18 . '09 23:02
source share



All Articles