Resharper convention for "event subscription on fields" to start with uppercase? - c#

This question is based on the original message that you find here:
ReSharper conventions for names of event handlers
I have the same question like the commenter on the second answer: Is it possible to let the Event subscription by default start with an uppercase letter? So if the button is called "btnOK", generate a method called "Btn"?
And before you asked, I'm aware of Jon Skeets answer, but still am curious if this is possible.
Thanks in advance!

For any event added in code/xaml (e.g. added with ReSharper's Create Method) the Naming Style settings of ReSharper will apply (see ReSharper->Options->Code Editing->C#->Naming Style).
As for anything named by the Designer View you have to stick to renaming. You could speed up things a little by using Refactoring Rename (Ctrl+R+R). Once the dialog is open press down array and use the first suggestion (which is also according to the set Naming Style).
You could of course always make a feature request at JetBrains but I think it is quite likely what you want is not possible because otherwise I think they would already have added such a feature. Still asking wont do any harm.

Related

Resharper - keep named parameters when doing code cleanup

We've adopted a convention that when calling a C# function with a "non-obvious" parameter, we use a named parameter even when it's not necessary.
E.g.
obj.Process(save: true)
rather than
obj.Process(true)
While it's unnecessary, it makes it a lot easier when glancing through the code to see what's going on, particularly with booleans or magic numbers.
However, resharper's code cleanup has a habit of removing these. I haven't been able to find a way to tell it to keep named parameters - is there one?
Although you can achieve it by doing what #EricWalker said, I want to propose another option.
You can start up the ReSharper options, look for Inspection Severity then go to Redundant explicit argument name specification and change this to do not show. This way you won't lose all the other good cleanups (like removing full name qualifiers) that remove redundant code offers.
In ReSharper 2018.1
There are two relevant steps. You will likely want to do both, but it depends on how you want ReSharper configured.
First, in Resharper -> Options -> Code Inspection -> Inspection Severity, disable the "Use preferred argument style for literal values" code style. (For bools, "[..] for literal values" is the relevant setting, though I chose to disable all of them.)
This setting is also linked to the ReSharper -> Options -> Code Editing -> Code Style -> Arguments settings, so these should now be automatically changed to "Do not show" instead of "Hint":
Second, the default ReSharper Code Cleanup profile cannot be used due to the "Apply arguments style (named vs. positional)" - this option must be disabled in your code cleanup profile.
To show argument names in your method calls, goto:
Resharper ⇨ Options ⇨ Code Editing ⇨ C# ⇨ Syntax Style ⇨ Arguments
Then set all dropdown values to "Named Argument."
Also, check "Skip single arguments" to show named parameters for the method only when there is more than one parameter.
The above approach was verified on Resharper version 2020.2.4
The setting you're looking for is under Code Cleanup\C#\Remove code redundancies
I know that's probably not the answer you were hoping for, but you can stop it removing your parameter names by unchecking that setting (along with leaving behind every other redundancy.)
You might be able to setup different profiles in Code Cleanup to work around the issue, but you'd have better luck asking JetBrains folks for solutions.
HTH,
Eric
UPDATE:
It seems that this solution no longer works starting with v2017.1.3 (2017-08-28)
I'm currently using ReSharper v2017.1 (2017-06-01) and it seems JetBrains hasn't solved this problem yet.
As #Colin Harkness noticed, currently the last resort for keeping "named parameters" is to set the option "Named expressions (variables, properties, methods, etc)" to "Named argument".
This is certainly not the best way out.
UPDATE:
I a little trick found at JetBrains' forum.
You can cancel considering named parameters as a redundancy by adding this line of code at the top of file.
// ReSharper disable ArgumentsStyleNamedExpression
You have to do some minor configuration within ReSharper settings. In order to keep automatic addition of the // ReSharper disable ArgumentsStyleNamedExpression simple, I have added this instruction to File Header Text as is shown in fig. 2.
Fig.2 - Add ArgumentsStyleNamedExpression Rule
After that, you have to check Update File Header option in Code Cleanup Configuration as is shown in fig. 3
Fig.3 - Check "Update File Header" option
In this case, when a Code Cleanup starts, it first adds ArgumentsStyleNamedExpression rule, and applies code style to file.
After adding this rule, you can go to Tools | Options | Environment | Fonts and Colors | ReSharper Parameter Identifier and change the highlighting color for this case in order to visually distinguish arguments and parameters names as is shown in fig 4.
Fig.4 - Parameter name highlighting
Unfortunately, this way of keeping arguments' names doesn't always work (ReSharper can selectively keep/remove names of arguments).

What makes it so that not every event is available in the designer, and how can I quickly generate handlers in C# like in VB.NET?

In the Visual Studio form designer, you can add an event handler on the Properties window in the "Events" list by double-clicking it. You can also add an event handler — at least in VB.NET — in the code view by selecting the associated "Events" item in the left-hand drop-down and then the desired event in the right-hand drop-down. My question is: how is it that some events that are only available via the latter technique and not the former? For example, the HandleCreated event is available in the code view:
But not in the designer:
This is fine in VB.NET because I can always use the first technique to quickly generate the event handlers. However, in C#, the first technique is not possible, yet the problem still exists; that is, some events are not present in the designer list in the Properties window. The only other way I know of creating the event handler is to manually add it, which includes manually wiring up the event handler.
Is there something technical that makes it so that some events are missing from the designer Events list in the Properties window? Given that that is true, how can I quickly generate event handlers in C# like I can in VB.NET?
Well, it is hidden intentionally. If you look at Control class, HandleCreated event is marked with Browsable(false) which means not to show it in properties window.
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Advanced)]
public event EventHandler HandleCreated;
If you ask me why? I don't know the answer. It is a design decision, which any of the person from design team have to answer that.
My guess is that they hide events which are not of more importance. How many times you need to subscribe HandleCreated? You typically subscribe Load event.
Some other good examples of events which falls under same category are ControlAdded, ControlRemoved etc. As you can see these are not very much important, they are hidden from designer.
How to easily subscribe the event in C# editor as like VB.net?
You cannot get the combobox for events as you get for VB.net; Closest what you can get is the ide support which can autocomplete for you (which is already mentioned in #HenkHolterman's answer; now deleted).
type this.HandleCreated += , then tab, tab.
Ide will hook up the events for you.
The VB.NET and the C# IDEs only look superficially the same. They worked from a pretty decent look-and-feel specification. But that's where the resemblance stops, they were created by two very different groups at Microsoft and have drastically different code-bases. Otherwise a survival strategy for large software companies, big groups don't work.
Most importantly, they had dramatically different goals. The C# team had the luxury of starting completely from scratch, always nice when you don't have anybody to keep happy and have no baggage to lug around. Not so for the VB.NET team, Visual Basic has been a popular product for a very long time with strong IDE support that goes back 25 years. Most important for them was to give their customers a familiar experience back, VB.NET was already a major upheaval that was very controversial.
The way those two combo-boxes at the top of the edit window work was cast in granite bedrock stone. They never filtered anything before. If the VB.NET programmer wrote an event handler for an event then he expects to always find it back in the combobox. It works the other way around as well, the VB.NET IDE hides a lot of information. Like not showing the auto-generated source files in the Solution Explorer window.
Don't make too many assumptions about how it should work, you're likely to guess wrong. And have few options to do something about it.
Imagine you have a user-control which has both UI and non-UI properties. You need to decorate non-UI properties with Browsable(False) so that they will not be available through the properties window.
To answer your second question, you can't quickly create event handlers as you would in VB.NET. This is one of the differences of VB.NET to C# beyond syntax.
In VB.NET, you can decorate a field with the WithEvents modifier, which is a requirement for creating "quick event handlers". This translates to a new property that will do all the event registration stuff for you. This WithEvents is implicitly created for the this (or Me) pointer as well. C# does not have this syntax feature and thus, it is not possible, so you have to do that manually. After all, the difference between VB.NET and C# has never been only syntax, just almost only syntax :)
I guess the reason is that C# was designed to restrict the amount of keywords to a bare minimum, whereas Microsoft never hestitated to add more keywords to VB.NET. If you consider the LINQ syntax elements, there are a couple of more keywords newly introduced into VB.NET than into C#.

Comments at end of method best practice?

I have some code which has comments after each method saying this for example:
// End of contructor DbFactoryDBConnection()
Should a comment like this be used to indicate the end of a method or not? It was something picked up from an earlier employment where it was common place.
I feel such comments are after methods which body does not fit in a single screen. I believe this is a good sign for the refactoring and splitting out such long methods to shorten ones or even extracting new entities/services/helpers. This is like C# region, sometimes it is used to hide very long code blocks and this is a sign that you have some kind of a God Object anti-patter.
No. If you want to know what the braces are closing, without scrolling, you can have ReSharper. Which is great in many ways.
Just put your cursor on braces, and if the opening of them isn't in view - it tooltips the whole line before it.
Usually this kind of comments are an overdocumentation hassle.
The right place where a comments should exist are at the beginning of your classes and of your methods and just before where important decisions will be taken inside your code.
If you find the need to document the end of an IF, SWITCH or METHOD then it's very probable that your code should be reexamined to be simplified.
I think this sort of commenting is completely unnecessary, and only serves to clutter the code. Most IDE's (such as Visual Studio) have had features for highlighting the scope of a method (or whatever) for many years, so i'm not sure what value you could add you your code by doing this.
You can always use PowerCommands for Visual Studio it add at end of braces comment what bracer end you are at i use it and it helps a lot:)
No, such a comment should not be used. The only reason, someone would use a comment like this is the fact that the method is way too long. But even than, modern IDEs show you somewhere in which method you currently are and even allows folding methods back to just the definition.
Comments like this are of no value whatsoever and simply pollute the code-base.
This doesn't belong in the source IMHO; it's too easy to get out of sync with the effective source code blocks. There are extensions that will show this info for you in Visual Studio i you thing that this is helpful.

Knowing when in design mode

From within a class library, I'd like to know if it is being accessed during design mode as opposed to normal runtime.
I tried using System.ComponentModel.LicenseManager.UsageMode but it seemed to have a value of Runtime even when I was editing a form.
UPDATE:
To clarify, I want to know if I am in design mode not from within a component, but rather from within a separate class that happens to be called by other items from within a form or control. I have a Utility class which is being called indirectly from a control and it is there that I need to know if I am in design mode or not.
I don't think Component.DesignMode will help in this case. What if the component or control is not loaded on the forms designer ? What you may try in this case is, create an enum that only sets the one value at normal startup which otherwise remains to another value by default. You can now check the value of the enum instance and decide if it's a design-time or runtime.
You can use Component.DesignMode to check this. However, be aware that this will always report false inside the constructor of the component, so it needs to be checked later. For details, see Debugging Design-Time Controls.
Edit in response to comments and edit:
Unfortunately, the LicenseMananger, as well as most other services which provide information about whether you're in Design Time (including Component.DesignMode and DesignerProperties.IsInDesignMode) as specifically geared at handling user interface elements. This makes sense, as they're intended to tell you when your item is being "designed" on a designer surface, which requires the component to be registered in the designer.
There is no single property that will cleanly tell you this from within an arbitrary class.
I could see two options, both of which are less than ideal:
Pass the required information into your class (ie: a Component or DependencyObject), so the methods above can be used to check for design-time access correctly. This is probably a more maintainable approach, and will likely work properly in more situations.
Resort to the "hack" of checking the current process name and looking for "devenv" - this is pretty awful, as it assumes Visual Studio only, relies on the executable name, etc... In general, I'll mention it because you'll find it with enough searching, but wouldn't recommend it, as it's very easy to circumvent and has many limitations and flaws.
Is it not possible to use Component.DesignMode property?
Here's some info on applying attributes in order to get design-time specific behavior: http://msdn.microsoft.com/en-us/library/37899azc.aspx

Why shouldn't I prefix my fields? [closed]

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.
I've never been a fan of Hungarian notation, I've always found it pretty useless unless you're doing some really low level programming, but in every C++ project I've worked on some kind of Hungarian notation policy was enforced, and with it the use of some 'not-really-Hungarian' prefixes as m_ for fields, s_ for statics, g_ for globals and so on.
Soon I realized how much useless it was in C# and gradually started to drop all of my old habits... but the 'm_' thing. I still use the m_ prefix on private fields because I really find it very useful to being able to distinguish between parameters, locals and fields.
The naming conventions for fields page at MSDN says I shouldn't, but it does not say why (the way e.g. Google's conventions generally tend to rationalize their prescriptions).
Are there reasons why I shouldn't or is it only a matter of style. If it is the latter, are prefixes generally considered a bad style and can I expect negative reactions from other people working on the codebase?
I like the underbar prefix for member fields. Mostly I like it because that way, all of my member fields are shown alphabetically before my methods in the wizard bar at the top of the screen.
When you should:
When your project coding guidelines say you should
When you shouldn't:
When your project coding guidelines say you shouldn't
If you don't have any guidelines yet, you're free to choose whatever you or your team want and feel most comfortable with. Personally when coding C++ I tend to use m_ for members, it does help. When coding in other languages, particularly those without true classes (like Javascript, Lua) I don't.
In short I don't believe there is a "right" and a "wrong" way.
The auto-implemented property feature in C# 3.0 creates less of a need for this convention one way or the other. 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 convention), you can now write
public string Name { get; private set; }
Since you no longer need the explicit backing store variable, you no longer have to come up with a name for it; thus avoiding this entire discussion.
Obviously, this argument doesn't apply when you really need explicit backing store such as to perform validation.
As some have alluded to, the MS guidelines say:
Do not use a prefix for field names.
For example, do not use g_ or s_ to
distinguish static versus non-static
fields.
I happen to agree with this. prefixes make your code look ugly and waste space with inconsequential characters. Having said that, it is often common to use fields to back properties where both the field and the property would have the same name (with the private field being camel case and the property being pascal case). In VB, this doesn't work, since VB isn't case-sensitive. In this scenario, I recommend the use of a single _ prefix. No more, no less. It just looks cleaner, IMHO.
I have experimented with m_, s_, just _, and no prefix at all. I have settled on using just _ for all static and instance variables. I don't find it important to distinguish static variables from instance variables. In theory it sounds good, in practice it doesn't create a problem.
A coworker once made a convincing argument to eliminate all prefixes, we tried it on one project and it worked better then I expected. I carried it forward to my next project and became annoyed that it "interferes" with Intellisense. When you have the following situation
int foo;
public int Foo
{
get { return foo; }
}
Starting to type foo will suggest both the instance variable and the property. Prefixing the variable with an underscore eliminates the annoying double suggestion, so I switched back to using just _.
I try to follow the MSDN .NET library guidelines. They include a naming guidelines section.
Obviously, these are secondary to your project guidelines.
I prefer to mark property backing fields (although as already mentioned .NET 3.0+ reduces the need thanks to Automatic Properties) with underscores but not the "m". For one it puts them at the top of the InteliSense list when I come to use them.
I will admit that I need to brush-up on the guidelines on MSDN, things can change so quickly these days.
With tools like resharper there's really no reason for prefixes. Also if you write short methods, you should be able to tell really quickly where the var is coming from. Finally, I guess I wouldn't really see the need to tell a difference between a static or not because again resharper is going to red line it if you try to do something you're not able to. Even without resharper you're probably saved by the compiler.
I always prefix member variables with m_ and static variables with s_ for the same reasons that you state. Some people prefix member variables with an underscore, but I've always found this a bit odd looking (but that's just a personal preference).
Most people I work with use the m_/s_ prefix. I don't really think it matters too much what you use, as long as you're consistent.
I never use them. It encourages sloppy coding.
The MSDN coding guidelines, that's where it's at.
Here are a few reasons to use _ (and not m_).
(1) Many BCL guys do it despite MS's naming guide. (Check out their blog.) Those guys write the framework, so they have some good habits worth copying. Some of the most helpful example code on MSDN is written by them, and so uses the underscore convention. It's a de-facto industry standard.
(2) A single underscore is a noticeable yet unobtrusive way to disambiguate method and class-level variables by simply reading the source. It helps people understand new (or old) code at-a-glance when reading it. Yes, you can mouse-over to see this in an IDE, but we shouldn't be forced to. You may want to read it in a text editor, or dare I say it, on paper.
(3) Some say you don't need any prefix as methods will be short, and later if needed you can change the field to an auto-implemented property. But in the real world methods are as long as they need to be, and there are important differences between fields and properties (e.g. serialization and initialization).
Footnote: The "m" for member in m_ is redundant in our usage here, but it was lower case because one of the ideas in many of these old naming conventions was that type names started with upper case and instance names started with lower case. That doesn't apply in .NET so it's doubly redundant. Also Hungarian notation was sometimes useful with old C compilers (e.g. integer or pointer casting and arithmetic) but even in C++ its usefulness was diminished when dealing with classes.
As #John Kraft mentions, there is no "correct" answer. MattJ is the closest–you should always follow your company's style guidelines. When in Rome, and all that.
As for my personal opinion, since it's called for here, I vote that you drop m_ entirely.
I believe the best style is one where all members are PascalCased, regardless of visibility (that means even private members), and all arguments are camelCased. I do not break this style.
I can understand the desire to prefix property backing store field; after all you must differentiate between the field and the property, right? I agree, you must. But use a post-fix.
Instead of m_MyProperty (or even _MyProperty, which I've seen and even promoted once upon a time), use MyPropertyValue. It's easier to read and understand and -- more importantly -- it's close to your original property name in intellisense.
Ultimately, that's the reason I prefer a postfix. If I want to access MyPropertyValue using intellisense you (typically) type "My <down-arrow> <tab>", since by then you're close enough that only MyProperty and MyPropertyValue are on the list. If you want to access m_MyProperty using intellisense, you'll have to type "m_My <tab>".
It's about keystroke economy, in my opinion.
There is one important difference between C++ and C#: Tool support. When you follow the established guidelines (or common variations), you will get a deep level of tool support that C++ never had. Following the standards allows tools to do deeper refactoring/rename operations than you'd otherwise be capable of. Resharper does this. So stick with one of the established standards.
I never do this and the reason why is that I [try to] keep my methods short. If I can see the whole method on the screen, I can see the params, I can see the locals and so I can tell what is owned by the class and what is a param or a local.
I do typically name my params and locals using a particular notation, but not always. I'm nothing if not inconsistent. I rely on the fact that my methods are short and try to keep them from doing X, Y and Z when they should be only doing X.
Anyhow, that's my two cents.
Unless I'm stuck with vi or Emacs for editing code, my IDE takes care of differential display of members for me so I rarely uses any special conventions. That also goes for prefixing interfaces with I or classes with C.
Someone, please, explain the .NET style of I-prefix on interfaces. :)
what i am used to is that private properties got small underscone f.ex "string _name". the public one got "Name". and the input variables in methods got small letter"void MyMethod(string name)".
if you got static const is often written with big letters. static const MYCONST = "hmpf".
I am sure that I will get flamed for this but so be it.
It's called Microsoft's .NET library guidelines but it's really Brad Abrams's views (document here) - there are other views with valid reasons.
People tend to go with the majority view rather than having good solid reasons for a specific style.
The important point is to evaluate why a specific style is used and why it's preferred over another style - in other words, have a reason for choosing a style not just because everyone says it's the thing to do - think for yourself.
The basic reason for not using old style Hungarian was the use of abbreviations which was different for every team and difficult to learn - this is easily solved by not abbreviating.
As the available development tools change the style should change to what makes the most sense - but have a solid reason for each style item.
Below are my style guidelines with my reasons - I am always looking for ways to improve my style to create more reliable and easier to maintain code.
Variable Naming Convention
We all have our view on variable naming conventions. There are many different styles that will help produce easily maintainable quality code - any style which supports the basic essential information about a variable are okay. The criteria for a specific naming convention should be that it aids in producing code that is reliable and easily maintainable. Criteria that should not be used are:
It's ugly
Microsoft (i.e. Brad Abrams) says don't use that style - Microsoft does not always produce the most reliable code just look at the bugs in Expression Blend.
It is very important when reading code that a variable name should instantly convey three essential facts about the variable:
it’s scope
it’s type
a clearly understand about what it is used for
Scope: Microsoft recommends relying totally on IntelliSense . IntelliSense is awesome; however, one simply does not mouse over every variable to see it's scope and type. Assuming a variable is in a scope that it is not can cause significant errors. For example, if a reference variable is passed in as a parameter and it is altered in local scope that change will remain after the method returns which may not be desired. If a field or a static variable is modified in local scope but one thinks that it is a local variable unexpected behavior could result. Therefore it is extremely important to be able to just look at a variable (not mouse over) and instantly know it's scope.
The following style for indicating scope is suggested; however, any style is perfectly okay as long as it clearly and consistently indicates the variable's scope:
m_ field variable
p_ parameter passed to a method
s_ static variable
local variable
Type: Serious errors can occur if one believes they are working with a specific type when they are actually working with a different type - again, we simply do not mouse over ever variable to determine its type, we just assume that we know what its type is and that is how errors are created.
Abbreviations: Abbreviations are evil because they can mean different things to different developers. One developer may think a leading lower case "s" means string while another may think it means signed integer. Abbreviations are a sign of lazy coding - take a little extra time and type the full name to make it clear to the developer that has to maintain the code. For example, the difference between "str" and "string" is only three characters - it does not take much more effort to make code easy to maintain.
Common and clear abbreviations for built-in data types only are acceptable but must be standardized within the team.
Self Documenting Code: Adding a clear description to a variable name makes it very easy for another developer to read and understand the code - make the name so understandable that the team manager can read and understand the code without being a developer.
Order of Variable Name Parts: The recommended order is scope-type-description because:
IntelliSense will group all similar scopes and within each scope IntelliSense will group all similar types which makes lookups easy - try finding a variable the other way
It makes it very easy to see and understand the scope and to see and understand the type
It's 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 significantly improve code reliability and maintainability.
Control Structure Single Line Statements
All control structures (if, while, for, etc.) single line statements should always be wrapped with braces because it is very easy to add a new statement not realizing that a given statement belongs to a control structure which will break the code logic without generating any compile time errors.
Method Exception Wrapping
All methods should be wrapped with an outer try-catch which trap, provide a place to recover, identify, locate, log, and make a decision to throw or not. It is the unexpected exception that cause our applications to crash - by wrapping every method trapping all unhandled exceptions we guarantee identifying and logging all exceptions and we prevent our application from ever crashing. It takes a little more work but the results is well worth the effort.
Indentation
Indentation is not a major issue; however, four spaces and not using tabs is suggested. If code is printed, the first printer tab usually defaults to 8 spaces. Different developer tend to use different tab sizes. Microsoft's code is usually indented 4 space so if one uses any Microsoft code and uses other than 4 spaces, then the code will need to be reformatted. Four spaces makes it easy and consistent.
I never use any hungarian warts whenever I'm given the choice. It's extra typing and doesn't convey any meaningful information. Any good IDE (and I define "good" based on the presence of this feature, among others) will allow you to have different syntax highlighting for static members, instance members, member functions, types, etc. There is no reason to clutter your code with information that can be provided by the IDE. This is a corollary to not cluttering your code with commented-out old code because your versioning system should be responsible for that stuff.
The best way is to agree on a standard with your colleagues, and stick to it. It doesn't absolutely have to be the method that would work best for everyone, just agreeing on one method is more important than which method you actually agree on.
What we chose for our code standard is to use _ as prefix for member variables. One of the reasons was that it makes it easy to find the local variables in the intellisense.
Before we agreed on that standard I used another one. I didn't use any prefix at all, and wrote this.memberVariable in the code to show that I was using a member variable.
With the property shorthand in C# 3, I find that I use a lot less explicit member variables.
The closest thing to official guidelines is StyleCop, a tool from Microsoft which can automatically analyse your source files and detect violations from the recommended coding style, and can be run from within Visual Studio and/or automated builds such as MSBuild.
We use it on our projects and it does help to make code style and layout more consistent between developers, although be warned it does take quite a bit of getting used to!
To answer your question - it doesn't allow any Hungarian notation, nor any prefixes like m_ (in fact, it doesn't allow the use of underscores at all).
I don't use that style any longer. It was developed to help you see quickly how variables were being used. The newer dev environments let you see that information by hovering your mouse over the variable. The need for it has gone away if you use those newer tools.
There might also be some insight to be gleaned from C++ Coding Standards (Sutter, Herb and Alexandrescum Andrei, 2004). Item #0 is entitled "Don't sweat the small stuff. (Or: Know what not to standardize.)".
They touch on this specific question a little bit by saying "If you can't decide on your own naming convention, try ... private member variables likeThis_ ..." (Remember use of leading underscore is subject to very specific rules in C++).
However, before getting there, they emphasize a certain level of consistency "...the important thing is not to set a rule but just to be consistent with the style already in use within the file..."
The benefit of that notation in C/C++ was to make it easier to see what a symbol's type was without having to go search for the declaration. These styles appeared before the arrival of Intellisense and "Go to Definition" - we often had to go on a goose chase looking for the declaration in who knows how many header files. On a large project this could be a significant annoyance which was bad enough when looking at C source code, but even worse when doing forensics using mixed assembly+source code and a raw call stack.
When faced with these realities, using m_ and all the other hungarian rules starts to make some sense even with the maintenance overhead because of how much time it would save just in looking up a symbol's type when looking at unfamiliar code. Now of course we have Intellisense and "Go to Definition", so the main time saving motivation of that naming convention is no longer there. I don't think there's much point in doing that any more, and I generally try to go with the .NET library guidelines just to be consistent and possibly gain a little bit more tool support.
If you are not coding under a particular guideline, you should keep using your actual m_ notation and change it if the project coding guidelines says so.
Be functional.
Do not use global variables.
Do not use static variables.
Do not use member variables.
If you really have to, but only if you really have to, use one and only one variable to access your application / environment.

Categories

Resources