Do you name controls on forms using the same convention as a private variable? - user-interface

For some reason I never see this done. Is there a reason why not? For instance I like _blah for private variables, and at least in Windows Forms controls are by default private member variables, but I can't remember ever seeing them named that way. In the case that I am creating/storing control objects in local variables within a member function, it is especially useful to have some visual distinction.

This might be counter-intuitive for some, but we use the dreaded Hungarian notation for UI elements.
The logic is simple: for any given data object you may have two or more controls associated with it. For example, you have a control that indicates a birth date on a text box, you will have:
the text box
a label indicating that the text box is for birth dates
a calendar control that will allow you to select a date
For that, I would have lblBirthDate for the label, txtBirthDate for the text box, and calBirthDate for the calendar control.
I am interested in hearing how others do this, however. :)

Hungarian notation or not, I'm more curious if people prepend m_ or _ or whatever they use for standard private member variables.

I personally prefix private objects with _
Form controls are always prefixed with the type, the only reason I do this is because of intellisense. With large forms it becomes easier to "get a labels value" by just typing lbl and selecting it from the list ^_^ It also follows the logic stated by Jon Limjap.
Although this does go again Microsofts .NET Coding Guidelines, check them out here.

For me, the big win with the naming convention of prepending an underscore to private members has to do with Intellisense. Since underscore precedes any letter in the alphabet, when I do a ctrl-space to bring up Intellisense, there are all of my _privateMembers, right at the top.
Controls, though, are a different story, as far as naming goes. I think that scope is assumed, and prepending a few letters to indicate type (txtMyGroovyTextbox, for example) makes more sense for the same reason; controls are grouped in Intellisense by type.
But at work, it's VB all the way, and we do mPrivateMember. I think the m might stand for module.

I came through VB and have held onto the control type prefix for controls. My private members use lower-camel case (firstLetterLowercase) while public members use Pascal/upper-camel case (FirstLetterUppercase).
If there are too many identifiers/members/locals to have a 90% chance of remembering/guessing what it is called, more abstraction is probably necessary.
I have never been convinced that a storage type prefix is useful and/or necessary. I do, however, make a strong habit of following the style of whatever code I am using.

I don't, but I appreciate your logic. I guess the reason most people don't is that underscores would look kind of ugly in the Properties window at design time. It'd also take up an extra character of horizontal space, which is at a premium in a docked window like that.

Hungarian notation or not, I'm more
curious if people prepend m_ or _ or
whatever they use for standard private
member variables.
Luke,
I use _ prefix for my class library objects. I use Hungarian notation exclusively for the UI, for the reason I stated.

I never use underscores in my variable names. I've found that anything besides alpha (sometimes alphanumeric) characters is excessive unless demanded by the language.

I'm in the Uppercase/Lowercase camp ("title" is private, "Title" is public), mixed with the "hungarian" notation for UI Components (tbTextbox, lblLabel etc.), and I am happy that we do not have Visual Case-Insensitive-Basic developers in the team :-)
I don't like the underscore because it looks kinda ugly, but I have to admit it has an advantage (or a disadvantage, depending on your point): In the debugger, all the private Variables will be on top due to the _ being on top of the alphabet. But then again, I prefer my private/public pair to be together, because that allows for easier debugging of getter/setter logic as you see the private and public property next to each other,

I write down the name of the database column they represent.

I use m_ for member variables, but I'm increasingly becoming tempted to just using lowerCamelCase like I do for method parameters and local variables. Public stuff is in UpperCamelCase.
This seems to be more or less accepted convention across the .NET community.

Related

What is the difference between Form5!ProgressBar.Max and Form5.ProgressBar.Max?

I'm looking at a piece of very old VB6, and have come across usages such as
Form5!ProgressBar.Max = time_max
and
Form5!ProgressBar.Value = current_time
Perusing the answer to this question here and reading this page here, I deduce that these things mean the same as
Form5.ProgressBar.Max = time_max
Form5.ProgressBar.Value = current_time
but it isn't at all clear that this is the case. Can anyone confirm or deny this, and/or point me at an explanation in words of one syllable?
Yes, Form5!ProgressBar is almost exactly equivalent to Form5.ProgressBar
As far as I can remember there is one difference: the behaviour if the Form5 object does not have a ProgressBar member (i.e. the form does not have a control called ProgressBar). The dot-notation is checked at compile time but the exclamation-mark notation is checked at run time.
Form5.ProgressBar will not compile.
Form5!ProgressBar will compile but will give an error at runtime.
IMHO the dot notation is preferred in VB6, especially when accessing controls. The exclamation mark is only supported for backward-compatibility with very old versions of VB.
The default member of a Form is (indirectly) the Controls collection.
The bang (!) syntax is used for collection access in VB, and in many cases the compiler makes use of it to early bind things that otherwise would be accessed more slowly through late binding.
Far from deprecated, it is often preferable.
However in this case since the default member of Form objects is [_Default] As Object containing a reference to a Controls As Object instance, there is no particular advantage or disadvantage to this syntax over:
Form5("ProgressBar").Value
I agree that in this case however it is better to more directly access the control as a member of the Form as in:
Form5.ProgressBar.Value
Knowing the difference between these is a matter of actually knowing VB. It isn't simply syntactic though, the two "paths" do different things that get to the same result.
Hopefully this answer offers an explanation rather merely invoking voodoo.

How to name GUI elements?

One thing that constantly causing me headache in programming is when I don't have any naming-convention in a domain where I have to deal with a lot elements. It is clearly what is happening to me when using UI designers such as Windows Forms designer.
Everytime I start a new project I am trying to reinvent a "seem-strong" naming convention but it always fail at some points. For me there is 2 main problems compared to classic code definition for naming GUI elements:
You have to place a lot of variables (GUI elements) which can all be accessed in the same scope, so you need to have to a strong naming convention to find quickly the right element.
You often need to access to a specific type of GUI control (ex: TextBox, Label, ...), so the best solution for GUI elements is to name them after their types (Hungarian style notation), which can be sometimes confusing and not helping in finding the right element quickly.
If someone has a documentation describing a good convention or a strong convention he invented for its own project, I would really like to know it!
NB: I did not classified this question under .NET or Windows Forms tags has it seems applicable to a lot of frameworks. If not, let me know.
EDIT:
In fact the convention I most use is using a reversed hungarian notation (meaning the type comes first) followed by a path based on the UI elements hierarchy. For example, to easily access to a TextBox which belongs to the "Settings" tab of my program I would call it this way:
this.tb_settingTab_xxx
My problem using this convention is that it is not perfect and sometimes fails when you have a UI element that belongs to another which also belongs to another which also belongs to ...
I am really searching for is the unbreakable and handy naming-convention. I am quitely surprised that Microsoft never gaved any guidelines concerning this. Or am I going wrong? (ie. Mark Rushakoff comment).
There are various naming conventions described in this post. The key is to remain consistent throughout the project. I deal with a lot of controls, but find it straightforward to label them based on what they are. Textbox = tbMyControl, Label = lblMyControl. The 'MyControl' bit might be the same if they relate to similar aspects (e.g. tbUsername, lblUsername). However, there's no confusion on what I'm accessing. If you find you're getting confused, then maybe you're trying too many different notations? Keep it simple and logical.
Note: I use the following in code that covers - and sometimes mixes - "raw" Win32, ATL/WTL and MFC, so don't take it literally, only the principle. (Also, be forgiving on the m_)
I use a two-letter-shortcut for standard control types, followed by the name which resembles the functionality of the control (in most cases, Identical / close to the label). The name of related controls needs to match of course - e.g.
CStatic m_stBasePath;
CEdit m_edBasePath;
CButton m_cbBrowseBasePath;
It's not perfect for all scenarios, but generally I'd say a dialog where this isn't good enough anymore might have to many controls for the user already.
I've written three paragraphs that could be titled "details and defense" - and subsequently deleted them, since there's a very clear essence:
Consistency.
I mostly use the dialog resource itself for orientation, and have strict equivalence between resource ID's and associated members. So the "Base path" - related controls aren#t together in an alphabetic order, but I rarely see this as a problem.
The standard control type already contains very obvious information about functionaltiy of a control - a checkbox to enable / disable a group of features or for a boolean option, an edit or drop down to enter/select a value, a button to open a sub dialog, a static control for the label, etc.
I'm not sure how this style transfers if you transfer it to a platform with much more controls or when you use a lot of custom controls, as my WinForms projects have been comparedly small.

Do you use articles in your variable names?

Edit: There appears to be at least two valid reasons why Smalltalkers do this (readability during message chaining and scoping issues) but perhaps the question can remain open longer to address general usage.
Original: For reasons I've long forgotten, I never use articles in my variable names. For instance:
aPerson, theCar, anObject
I guess I feel like articles dirty up the names with meaningless information. When I'd see a coworker's code using this convention, my blood pressure would tick up oh-so-slightly.
Recently I've started learning Smalltalk, mostly because I want to learn the language that Martin Fowler, Kent Beck, and so many other greats grew up on and loved.
I noticed, however, that Smalltalkers appear to widely use indefinite articles (a, an) in their variable names. A good example would be in the following Setter method:
name: aName address: anAddress.
self name: aName.
self address: anAddress
This has caused me to reconsider my position. If a community as greatly respected and influential as Smalltalkers has widely adopted articles in variable naming, maybe there's a good reason for it.
Do you use it? Why or why not?
This naming convention is one of the patterns in Kent Beck's book Smalltalk Best Practice Patterns. IMHO this book is a must-have even for non-smalltalkers, as it really helps naming things and writing self-documenting code. Plus it's probably one of the few pattern langages to exhibit Alexander's quality without a name.
Another good book on code patterns is Smalltalk with Style, which is available as a free PDF.
Generally, the convention is that instance variables and accessors use the bare noun, and parameters use the indefinite article plus either a role or a type, or a combination. Temporary variables can use bare nouns because they rarely duplicate the instance variable; alternatively, it's quite frequent to name them with more precision than just an indefinite article, in order to indicate their role in the control flow: eachFoo, nextFoo, randomChild...
It is in common use in Smalltalk as a typeless language because it hints the type of an argument in method call. The article itself signals that you are dealing with an instance of some object of specified class.
But remember that in Smalltalk the methods look differently, we use so called keyword messages and it this case the articles actually help the readability:
anAddressBook add: aPerson fromTownNamed: aString
I think I just found an answer. As Konrad Rudolph said, they use this convention because of a technical reason:
...this means it [method variable] cannot duplicate the name of an instance variable, a temporary variable defined in the interface, or another temporary variable.
-IBM Smalltalk Tutorial
Basically a local method variable cannot be named the same as an object/class variable. Coming from Java, I assumed a method's variables would be locally scoped, and you'd access the instance variables using something like:
self address
I still need to learn more about the method/local scoping in Smalltalk, but it appears they have no other choice; they must use a different variable name than the instance one, so anAddress is probably the simplest approach. Using just address results in:
Name is already defined ->address
if you have an instance variable address defined already...
I always felt the articles dirtied up the names with meaningless information.
Exactly. And this is all the reason necessary to drop articles: they clutter the code needlessly and provide no extra information.
I don’t know Smalltalk and can't talk about the reasons for “their” conventions but everywhere else, the above holds. There might be a simple technical reason behind the Smalltalk convention (such as ALL_CAPS in Ruby, which is a constant not only by convention but because of the language semantics).
I wobble back and forth on using this. I think that it depends on the ratio of C++ to Objective C in my projects at any given time. As for the basis and reasoning, Smalltalk popularized the notion of objects being "things". I think that it was Yourdon and Coad that strongly pushed describing classes in the first person. In Python it would be something like the following snippet. I really wish that I could remember enough SmallTalk to put together a "proper" example.
class Rectangle:
"""I am a rectangle. In other words, I am a polygon
of four sides and 90 degree vertices."""
def __init__(self, aPoint, anotherPoint):
"""Call me to create a new rectangle with the opposite
vertices defined by aPoint and anotherPoint."""
self.myFirstCorner = aPoint
self.myOtherCorner = anotherPoint
Overall, it is a conversational approach to program readability. Using articles in variable names was just one portion of the entire idiom. There was also an idiom surrounding the naming of parameters and message selectors IIRC. Something like:
aRect <- [Rectangle createFromPoint: startPoint
toPoint: otherPoint]
It was just another passing fad that still pops up every so often. Lately I have been noticing that member names like myHostName are popping up in C++ code as an alternative to m_hostName. I'm becoming more enamored with this usage which I think hearkens back to SmallTalk's idioms a little.
Never used, maybe because in my main language there are not any articles :P
Anyway i think that as long as variable's name is meaningful it's not important if there are articles or not, it's up to the coder's own preference.
Nope. I feel it is waste of characters space and erodes the readability of your code. I might use variations of the noun, for example Person vs People depending on the context. For example
ArrayList People = new ArrayList();
Person newPerson = new Person();
People.add(newPerson);
No I do not. I don't feel like it adds anything to the readability or maintainability of my code base and it does not distinguish the variable for me in any way.
The other downside is if you encourage articles in variable names, it's just a matter of time before someone does this in your code base.
var person = new Person();
var aPerson = GetSomeOtherPerson();
Where I work, the standard is to prefix all instance fields with "the-", local variables with "my-" and method parameters with "a-". I believe this came about because many developers were using text editors like vi instead of IDE's that can display different colors per scope.
In Java, I'd have to say I prefer it over writing setters where you dereference this.
Compare
public void setName(String name) {
this.name = name;
}
versus
public void setName(String aName) {
theName = aName;
}
The most important thing is to have a standard and for everyone to adhere to it.

What kind of prefix do you use for member variables?

No doubt, it's essential for understanding code to give member variables a prefix so that they can easily be distinguished from "normal" variables.
But what kind of prefix do you use?
I have been working on projects where we used m_ as prefix, on other projects we used an underscore only (which I personally don't like, because an underscore only is not demonstrative enough).
On another project we used a long prefix form, that also included the variable type. mul_ for example is the prefix of a member variable of type unsigned long.
Now let me know what kind of prefix you use (and please give a reason for it).
EDIT: Most of you seem to code without special prefixes for member variables! Does this depend on the language? From my experience, C++ code tends to use an underscore or m_ as a prefix for member variables. What about other languages?
No doubt, it's essential for understanding code to give member variables a prefix so that they can easily be distinguished from "normal" variables.
I dispute this claim. It's not the least bit necessary if you have half-decent syntax highlighting. A good IDE can let you write your code in readable English, and can show you the type and scope of a symbol other ways. Eclipse does a good job by highlighting declarations and uses of a symbol when the insertion point is on one of them.
Edit, thanks slim: A good syntax highlighter like Eclipse will also let you use bold or italic text, or change fonts altogether. For instance, I like italics for static things.
Another edit: Think of it this way; the type and scope of a variable are secondary information. It should be available and easy to find out, but not shouted at you. If you use prefixes like m_ or types like LPCSTR, that becomes noise, when you just want to read the primary information – the intent of the code.
Third edit: This applies regardless of language.
I do not use any prefix at all. If I run into danger of mixing up local variables or method parameters with class members, then either the method or the class is too long and benefits from splitting up.
This (arguably) not only makes the code more readable and somewhat "fluent", but most importantly encourages well structured classes and methods. In the end, it thus boils down to a completely different issue than the prefix or no-prefix dillema.
UPDATE: well, taste and preferences change, don't they.. I now use underscore as the prefix for member variables as it has proven to be beneficial in recognizing local and member variables in the long run. Especially new team members sometimes have hard time when the two are not easily recognizable.
None. I used to use underscore, but was talked out of it on a project where the others didn't like it, and haven't missed it. A decent IDE or a decent memory will tell you what's a member variable and what isn't. One of the developers on our project insists on putting "this." in front of every member variable, and we humour him when we're working on areas of code that are nominally "his".
Underscore only.
In my case, I use it because that's what the coding standards document says at my workplace. However, I cannot see the point of adding m_ or some horrible Hungarian thing at the beginning of the variable. The minimalist 'underscore only' keeps it readable.
It's more important to be consistent than anything, so pick something you and your teammates can agree upon and stick with it. And if the language you're coding in has a convention, you should try to stick to it. Nothing's more confusing than a code base that follows a prefixing rule inconsistently.
For c++, there's another reason to prefer m_ over _ besides the fact that _ sometimes prefixes compiler keywords. The m stands for member variable. This also gives you the ability disambiguate between locals and the other classes of variables, s_ for static and g_ for global (but of course don't use globals).
As for the comments that the IDE will always take care of you, is the IDE really the only way that you're looking at your code? Does your diff tool have the same level of quality for syntax hilighting as your IDE? What about your source control revision history tool? Do you never even cat a source file to the command line? Modern IDE's are fantastic efficiency tools, but code should be easy to read regardless of the context you're reading it in.
I prefer using this keyword.
That means this.data or this->data instead of some community-dependent naming.
Because:
with nowadays IDEs typing this. popups intellinsense
its obvious to everyone without knowing defined naming
BTW prefixing variables with letters to denote their type is outdated with good IDEs and reminds me of this Joel's article
We use m_ and then a slightly modified Simonyi notation, just like Rob says in a previous response. So, prefixing seems useful and m_ is not too intrusive and easily searched upon.
Why notation at all? And why not just follow (for .NET) the Microsoft notation recommendations which rely upon casing of names?
Latter question first: as pointed out, VB.NET is indifferent to casing. So are databases and (especially) DBAs. When I have to keep straight customerID and CustomerID (in, say, C#), it makes my brain hurt. So casing is a form of notation, but not a very effective one.
Prefix notation has value in several ways:
Increases the human comprehension of code without using the IDE. As in code review -- which I still find easiest to do on paper initially.
Ever write T-SQL or other RDBMS stored procs? Using prefix notation on database column names is REALLY helpful, especially for those of us who like using text editors for this sort of stuff.
Maybe in short, prefixing as a form of notation is useful because there are still development environments where smart IDEs are not available. Think about the IDE (a software tool) as allowing us some shortcuts (like intellisense typing), but not comprising the whole development environment.
An IDE is an Integrated Development Environment in the same way that a car is a Transportation Network: just one part of a larger system. I don't want to follow a "car" convention like staying on marked roads, when sometimes, its faster just to walk through a vacant lot. Relying on the IDE to track variable typing would be like needing the car's GPS to walk through the vacant lot. Better to have the knowledge (awkward though it may be to have "m_intCustomerID") in a portable form than to run back to the car for every small change of course.
That said, the m_ convention or the "this" convention are both readable. We like m_ because it is easily searched and still allows the variable typing to follow it. Agreed that a plain underscore is used by too many other framework code activities.
Using C#, I've moved from the 'm_'-prefix to just an underscore, since 'm_' is an heritage from C++.
The official Microsoft Guidelines tells you not to use any prefixes, and to use camel-case on private members and pascal-case on public members. The problem is that this collides with another guideline from the same source, which states that you should make all code compatible with all languages used in .NET. For instance, VB.NET doesn't make a difference between casings.
So just an underscore for me. This also makes it easy to access through IntelliSense, and external code only calling public members don't have to see the visually messy underscores.
Update: I don't think the C# "this."-prefix helps out the "Me." in VB, which will still see "Me.age" the same as "Me.Age".
It depends on which framework I'm using! If I'm writing MFC code then I use m_ and Hungarian notation. For other stuff (which tends to be STL/Boost) then I add an underscore suffix to all member variables and I don't bother with Hungarian notation.
MFC Class
class CFoo
{
private:
int m_nAge;
CString m_strAddress;
public:
int GetAge() const { return m_nAge; }
void SetAge(int n) { m_nAge = n; }
CString GetAddress() const { return m_strAddress;
void SetAddress(LPCTSTR lpsz) { m_strAddress = lpsz; }
};
STL Class
class foo
{
private:
int age_;
std::string address_;
public:
int age() const { return age_; }
void age(int a) { age_ = a; }
std::string address() const { return address_; }
void address(const std::string& str) { address_ = str; }
};
Now this may seem a bit odd - two different styles - but it works for me, and writing a lot of MFC code that doesn't use the same style as MFC itself just looks ugly.
I prefix member variables with 'm' and parameters (in the function) with 'p'. So code will look like:
class SomeClass {
private int mCount;
...
private void SomeFunction(string pVarName) {...}
}
I find that this quickly tells you the basic scope of any variable - if no prefix, then it's a local. Also, when reading a function you don't need to think about what's being passed in and what's just a local variable.
It really depends on the language.
I'm a C++ guy, and prefixing everything with underscore is a bit tricky. The language reserves stuff that begins with underscore for the implementation in some instances (depending on scope). There's also special treatment for double underscore, or underscore following by a capital letter. So I say just avoid that mess and simply choose some other prefix. 'm' is ok IMO. 'm_' is a bit much, but not terrible either. A matter of taste really.
But watch out for those _leadingUnderscores. You'll be surprised how many compiler and library internals are so named, and there's definitely room for accidents and mixup if you're not extremely careful. Just say no.
Most of the time, I use python. Python requires you to use self.foo in order to access the attribute foo of the instance of the current class. That way, the problem of confusing local variables, parameters and attributes of the instance you work on is solved.
Generally, I like this approach, even though I dislike being forced to do it. Thus, my ideal way to do thos is to not do it and use some form of attribute access on this or self in order to fetch the member variables. That way, I don't have to clutter the names with meta-data.
I'm weirdo and I prefix member variables with initials from the class name (which is camel-cased).
TGpHttpRequest = class(TOmniWorker)
strict private
hrHttpClient : THttpCli;
hrPageContents: string;
hrPassword : string;
hrPostData : string;
Most of the Delphi people just use F.
TGpHttpRequest = class(TOmniWorker)
strict private
FHttpClient : THttpCli;
FPageContents: string;
FPassword : string;
FPostData : string;
If the language supports the this or Me keyword, then use no prefix and instead use said keyword.
another trick is naming convention:
All member variables are named as usual, without any prefix (or 'this.' is it is usual to do so in the project)
But they will be easily differentiated from local variable because in my project, those local variables are always named:
aSomething: represents one object.
someManyThings: list of objects.
isAState or hasSomeThing: for boolean state.
Any variable which does not begin by 'a', 'some' or 'is/has' is a member variable.
Since VB.NET is not case-sensitive, I prefix my member variables with an underscore and camel case the rest of the name. I capitalize property names.
Dim _valueName As Integer
Public Property ValueName() As Integer
I'm with the people that don't use prefixes.
IDEs are so good nowadays, it's easy to find the information about a variable at a glance from syntax colouring, mouse-over tooltips and easy navigation to its definition.
This is on top of what you can get from the context of the variable and naming conventions (such as lowerCamelCase for local variables and private fields, UpperCamelCase for properties and methods etc) and things like "hasXXXX" and "isXX" for booleans.
I haven't used prefixes for years, but I did used to be a "this." prefix monster but I've gone off that unless absolutely necessary (thanks, Resharper).
A single _ used only as a visual indicator. (C#)
helps to group members with intellisense.
easier to spot the member variables when reading the code.
harder to hide a member variable with a local definition.
_ instead of this.
I use _ too instead of this. because is just shorter (4 characters less) and it's a good indicator of member variables. Besides, using this prefix you can avoid naming conflicts. Example:
public class Person {
private String _name;
public Person(String name) {
_name = name;
}
}
Compare it with this:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
}
I find the first example shorter and more clear.
It kinda depends what language you're working in.
In C# you can reference any member using the 'this' prefix, e.g. 'this.val', which means no prefixes are needed. VB has a similar capability with 'Me'.
In languages where there is a built-in notation for indicating member access I don't see the point in using a prefix. In other languages, I guess it makes sense to use whatever the commonly accepted convention is for that language.
Note that one of the benefits of using a built-in notation is that you can also use it when accessing properties and methods on the class without compromising your naming conventions for those (which is particularly important when accessing non-private members). The main reason for using any kind of indicator is as a flag that you are causing possible side effects in the class, so it's a good idea to have it when using other members, irrespective of whether they are a field/property/method/etc.
I use camel case and underscore like many here. I use the underscore because I work with C# and I've gotten used to avoiding the 'this' keyword in my constructors. I camel case method-scoped variants so the underscore reminds me what scope I'm working with at the time. Otherwise I don't think it matters as long as you're not trying to add unnecessary information that is already evident in code.
I've used to use m_ perfix in C++ but in C# I prefer just using camel case for the field and pascal case for its property.
private int fooBar;
public int FooBar
{
get { return fooBar; }
set { fooBar = value; }
}
I like m_ but as long as convention is used in the code base is used I'm cool with it.
Your mul_ example is heading towards Charles Simonyi's Apps Hungarian notation.
I prefer keeping things simple and that's why I like using m_ as the prefix.
Doing this makes it much easier to see where you have to go to see the original declaration.
I tend to use m_ in C++, but wouldn't mind to leave it away in Java or C#. And it depends on the coding standard. For legacy code that has a mixture of underscore and m_ I would refactor the code to one standard (given a reasonable code size)
I use #.
:D j/k -- but if does kind of depend on the language. If it has getters/setters, I'll usually put a _ in front of the private member variable and the getter/setter will have the same name without the _. Otherwise, I usually don't use any.
For my own projects I use _ as a postfix (as Martin York noted above, _ as a prefix is reserver by the C/C++ standard for compiler implementations) and i when working on Symbian projects.
In Java, one common convention is to preface member variables with "my" andUseCamelCaseForTheRestOfTheVariableName.
None if it's not necessary, single underscore otherwise. Applies for python.
If it is really necessary to prefix member variables, I would definitely prefer m_ to just an underscore. I find an underscore on its own reduces readability, and can be confused with C++ reserved words.
However, I do doubt that member variables need any special notation. Even ignoring IDE help, it isn't obvious why there would be confusion between what is a local and what is a member variable.

How do you feel about code folding? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
For those of you in the Visual Studio environment, how do you feel about wrapping any of your code in #regions? (or if any other IDE has something similar...)
9 out of 10 times, code folding means that you have failed to use the SoC principle for what its worth.
I more or less feel the same thing about partial classes. If you have a piece of code you think is too big you need to chop it up in manageable (and reusable) parts, not hide or split it up.It will bite you the next time someone needs to change it, and cannot see the logic hidden in a 250 line monster of a method.
Whenever you can, pull some code out of the main class, and into a helper or factory class.
foreach (var item in Items)
{
//.. 100 lines of validation and data logic..
}
is not as readable as
foreach (var item in Items)
{
if (ValidatorClass.Validate(item))
RepositoryClass.Update(item);
}
My $0.02 anyways.
This was talked about on Coding Horror.
My personal belief is that is that they are useful, but like anything in excess can be too much.
I use it to order my code blocks into:
Enumerations
Declarations
Constructors
Methods
Event Handlers
Properties
Sometimes you might find yourself working on a team where #regions are encouraged or required. If you're like me and you can't stand messing around with folded code you can turn off outlining for C#:
Options -> Text Editor -> C# -> Advanced Tab
Uncheck "Enter outlining mode when files open"
I use #Region to hide ugly and useless automatically generated code, which really belongs in the automatically generated part of the partial class. But, when working with old projects or upgraded projects, you don't always have that luxury.
As for other types of folding, I fold Functions all the time. If you name the function well, you will never have to look inside unless you're testing something or (re-)writing it.
While I understand the problem that Jeff, et. al. have with regions, what I don't understand is why hitting CTRL+M,CTRL+L to expand all regions in a file is so difficult to deal with.
I use Textmate (Mac only) which has Code folding and I find it really useful for folding functions, I know what my "getGet" function does, I don't need it taking up 10 lines of oh so valuable screen space.
I never use it to hide a for loop, if statement or similar unless showing the code to someone else where I will hide code they have seen to avoid showing the same code twice.
I prefer partial classes as opposed to regions.
Extensive use of regions by others also give me the impression that someone, somewhere, is violating the Single Responsibility Principle and is trying to do too many things with one object.
#Tom
Partial classes are provided so that you can separate tool auto-generated code from any customisations you may need to make after the code gen has done its bit. This means your code stays intact after you re-run the codegen and doesn't get overwritten. This is a good thing.
I'm not a fan of partial classes - I try to develop my classes such that each class has a very clear, single issue for which it's responsible. To that end, I don't believe that something with a clear responsibility should be split across multiple files. That's why I don't like partial classes.
With that said, I'm on the fence about regions. For the most part, I don't use them; however, I work with code every day that includes regions - some people go really heavy on them (folding up private methods into a region and then each method folded into its own region), and some people go light on them (folding up enums, folding up attributes, etc). My general rule of thumb, as of now, is that I only put code in regions if (a) the data is likely to remain static or will not be touched very often (like enums), or (b) if there are methods that are implemented out of necessity because of subclassing or abstract method implementation, but, again, won't be touched very often.
Regions must never be used inside methods. They may be used to group methods but this must be handled with extreme caution so that the reader of the code does not go insane. There is no point in folding methods by their modifiers. But sometimes folding may increase readability. For e.g. grouping some methods that you use for working around some issues when using an external library and you won't want to visit too often may be helpful. But the coder must always seek for solutions like wrapping the library with appropriate classes in this particular example. When all else fails, use folding for improving readibility.
This is just one of those silly discussions that lead to nowhere. If you like regions, use them. If you don't, configure your editor to turn them off. There, everybody is happy.
I generally find that when dealing with code like Events in C# where there's about 10 lines of code that are actually just part of an event declaration (the EventArgs class the delegate declaration and the event declaration) Putting a region around them and then folding them out of the way makes it a little more readable.
Region folding would be fine if I didn't have to manually maintain region groupings based on features of my code that are intrinsic to the language. For example, the compiler already knows it's a constructor. The IDE's code model already knows it's a constructor. But if I want to see a view of the code where the constructors are grouped together, for some reason I have to restate the fact that these things are constructors, by physically placing them together and then putting a group around them. The same goes for any other way of slicing up a class/struct/interface. What if I change my mind and want to see the public/protected/private stuff separated out into groups first, and then grouped by member kind?
Using regions to mark out public properties (for example) is as bad as entering a redundant comment that adds nothing to what is already discernible from the code itself.
Anyway, to avoid having to use regions for that purpose, I wrote a free, open source Visual Studio 2008 IDE add-in called Ora. It provides a grouped view automatically, making it far less necessary to maintain physical grouping or to use regions. You may find it useful.
I think that it's a useful tool, when used properly. In many cases, I feel that methods and enumerations and other things that are often folded should be little black boxes. Unless you must look at them for some reason, their contents don't matter and should be as hidden as possible. However, I never fold private methods, comments, or inner classes. Methods and enums are really the only things I fold.
My approach is similar to a few others here, using regions to organize code blocks into constructors, properties, events, etc.
There's an excellent set of VS.NET macros by Roland Weigelt available from his blog entry, Better Keyboard Support for #region ... #endregion. I've been using these for years, mapping ctrl+. to collapse the current region and ctrl++ to expand it. Find that it works a lot better that the default VS.NET functionality which folds/unfolds everything.
I personally use #Regions all the time. I find that it helps me to keep things like properties, declarations, etc separated from each other.
This is probably a good answer, too!
Coding Horror
Edit: Dang, Pat beat me to this!
The Coding Horror article actual got me thinking about this as well.
Generally, I large classes I will put a region around the member variables, constants, and properties to reduce the amount of text I have to scroll through and leave everything else outside of a region. On forms I will generally group things into "member variables, constants, and properties", form functions, and event handlers. Once again, this is more so I don't have to scroll through a lot of text when I just want to review some event handlers.
I prefer #regions myself, but an old coworker couldn't stand to have things hidden. I understood his point once I worked on a page with 7 #regions, at least 3 of which had been auto-generated and had the same name, but in general I think they're a useful way of splitting things up and keeping everything less cluttered.
I really don't have a problem with using #region to organize code. Personally, I'll usually setup different regions for things like properties, event handlers, and public/private methods.
Eclipse does some of this in Java (or PHP with plugins) on its own. Allows you to fold functions and such. I tend to like it. If I know what a function does and I am not working on it, I dont need to look at it.
Emacs has a folding minor mode, but I only fire it up occasionally. Mostly when I'm working on some monstrosity inherited from another physicist who evidently had less instruction or took less care about his/her coding practices.
Using regions (or otherwise folding code) should have nothing to do with code smells (or hiding them) or any other idea of hiding code you don't want people to "easily" see.
Regions and code folding is really all about providing a way to easily group sections of code that can be collapsed/folded/hidden to minimize the amount of extraneous "noise" around what you are currently working on. If you set things up correctly (meaning actually name your regions something useful, like the name of the method contained) then you can collapse everything except for the function you are currently editing and still maintain some level of context without having to actually see the other code lines.
There probably should be some best practice type guidelines around these ideas, but I use regions extensively to provide a standard structure to my code files (I group events, class-wide fields, private properties/methods, public properties/methods). Each method or property also has a region, where the region name is the method/property name. If I have a bunch of overloaded methods, the region name is the full signature and then that entire group is wrapped in a region that is just the function name.
I personally hate regions. The only code that should be in regions in my opinion is generated code.
When I open file I always start with Ctrl+M+O. This folds to method level. When you have regions you see nothing but region names.
Before checking in I group methods/fields logically so that it looks ok after Ctrl+M+O.
If you need regions you have to much lines in your class. I also find that this is very common.
region ThisLooksLikeWellOrganizedCodeBecauseIUseRegions
// total garbage, no structure here
endregion
Enumerations
Properties
.ctors
Methods
Event Handlers
That's all I use regions for. I had no idea you could use them inside of methods.
Sounds like a terrible idea :)

Resources