views:

2154

answers:

21

I was wondering how people name variables, objects, and function names with all the combination's out there; camel-case, pascal, using underscores, all caps for statics etc....

A good naming convention that is uniform could create a quicker understanding of what the item is, leading to much faster interpretations...e.g. 'oh its all in caps, so I KNOW its a static var'...'oh the function is in camel case so I know that it's a non-static call'... etc...

I have even seen some people who include the return type in a function name like:

int myFunction_int(); // the '_' is a delimiter for the return type
string myFunction_string();

Just curious what convention's people use since some people come from c++ probably use the underscores more than the Java folks.

More Examples

int g_my_global;
int gMyGlobal;

int _age;
int Age {get; set;}

int* p_my_pointer;
int* pMyPointer;

static int MYSTATIC = 1;

static void MyFunction();
void my_function();
void myFunction();
+37  A: 

I like pascal or camel casing, with every word spelled out completely. No abbreviations, prefixes, suffixes, hungarian notations, underscores, etc. - just words!

Andy White
Totally agree, though there are some rare abbreviations I don't mind, like Id (Identification) or Info (Information). I despise underscores :)
Gordon Tucker
I'm a little more liberal on abbreviations--I'll abbreviate a long word if it's totally clear from context what it must be. In a bunch of stuff about customers I would probably do Cust, but in something that only briefly touched on customers I would spell it out.
Loren Pechtel
Yeah, I guess the abbreviation thing is a little looser than I said originally. I always abbreviate things that would be ridiculous to spell out, like Id, Http, Sql, etc. The two-letter acronyms are a bit of a pain point though... Some people prefer to stay with the convention of first letter capital only, but "Framework Design Guidelines" says that 2 letter acronyms should be all capital...
Andy White
Agreed on Id with a small d: I hate it when you have SomethingID everywhere, it makes the code look inconsistent.
Ed Woodcock
Yea I like everything spelled out to. So I can get the an idea of what the function or variable does or is just from the name.
gmcalab
I like this... until I get aReallyLongVariableNameThatGoesOnForever
Matthew Whited
+14  A: 

I think it depends heavily on which language you are using. Is the language type-safe, compiled or interpreted?

In a type safe language you don't need to prefix the variables with the datatype to keep your code understandable.

Here's what I do in C#:

Fields              int _age;
Properties          public int Age { get; set; }
Constants           int cNoOfFeet = 2;    (the way I prefer it)
                    int NumberOfFeet = 2    (the way Microsoft likes it)

Constructor         internal Person (string name, int age) { ... }
Method              public static Person GetPerson (int personId) { ... }

Local variables     int newAge = age + 1;

Controls            lblFirstName, btnOK, lstPersons

var usage           int number = 10;    instead of    var number = 10;
                    var stuff = new Dictionary<Person, List<Persons>>();
                    (code should be readable, var number = 10, makes it worse)

So as you can see, I prefer Camel-case and I despise underscores in everything but fields. Abbreviations are ok, but use them wisely (e.g. number of people: noOfPeople is ok, noOfPpl is not).

Hey and if you lack inspiration: http://www.classnamer.com/ ;)

Edit:
Another useful one: http://www.irritatedvowel.com/Programming/Standards.aspx

Zyphrax
I definitely follow some ideas of yours, but i omit the underscore for the fields...
gmcalab
In the .NET framework Microsoft now uses Pascal case for constants, no abbreviations.
280Z28
+1 for classnamer
Mark
I don't like the underscore either. And why on earth have a c infront of the constant... that's just ugly :p I would also have written `NumberOfPeople` as it is *so* much more readable... and with intellisense and ReSharper, it's not any more typing anyways.
Svish
@Svish: In Visual Studio 2010, you can type it with "NOP" (CamelCase matching) as well, or with "people" (substring matching). Substring matching is a godsend with things like APIs that use enumerations where every element starts with `SOMEENUMITEM_`, etc.
280Z28
@280Z28: Yup, looking forward to VS2010 =)
Svish
Underscores on fields - yuck. There are naming conventions you know, follow them if you are writing code others will use: http://goo.gl/fjTL
Callum Rogers
@Callum/Gmcalab: from what I see there are two "standards" used by Microsoft. The underscore prefix or the this. prefix. I prefer the underscore, because it is easier with Intellisense. I believe that StyleCop now suggests you should use the this. prefix.
Zyphrax
Shouldn't those constants be "const int NumberOfFeet = 2" or else how are they not variables?
Jared Updike
This is basically exactly my convention I use, +1 for the _ on fields, this is an important specification as guarantees your field name usage will always be CLS-Compliant.
Chris Marisic
I agree with all of this... except I like to "var" the hell out of my code. I find it make my code much easier to refactor later.
Matthew Whited
+1 for classnamer that is pretty funny
wsanville
+9  A: 

You might like to view this for C#

Ravisha
Very good. It's almost exactly what I do, although I do tend to put short acronyms in all caps and I would do iFoo rather than IFoo.
Loren Pechtel
Ick, using CapitalCamelCase for everything makes methods look like types to my Java-trained eyes.
Robert Fraser
@Robert Welcome to .Net C# world .Get used should type cast ur self to a c# developer if u dnt find it amusing
Ravisha
+3  A: 

All I have to say is that in C++, the ALL_CAPS convention for constants is not a good idea, because preprocessor macros usually use that convention. Macros merely perform simple text substitutions and are not aware of language features like namespaces. Macros will therefore happily clobber your innocent little namespaced constants.

Google uses kConstantName in their coding style guide. An alternative that somewhat preserves the traditional style would be k_CONSTANT_NAME.

I wanted to use the name "null" a while back in one of my enumerations, and this is what led me to abandon the ALL_CAPS convention for constants.

Emile Cormier
All caps for macros are nice because it alerts you to be careful. Having anything else in caps is "crying wolf." kConstantName dates way back and bridges styles… but are enumerations still so common? Also, you made an `enum` constant to shadow `NULL`???
Potatoswatter
I was writing a C++ wrapper around the shapelib library. The shape types are null, point, polyline, polygon, etc. It bothered me that I had to use a synonym for null instead of using the domain's preferred word.
Emile Cormier
Good point about "crying wolf". After switching to Google's style, I liked that my constants didn't stand out as much compared to variables.
Emile Cormier
@Potatoswatter atleast in C# Enumerations if left unset default to the first value of the enum which can be confusing whether or not it was ever set. Alot of my enums are defined with Null = 0, as the very first entry. I also love using nullable enums so I can do GetValueOrDefault() == EnumName.Null comparisons.
Chris Marisic
+1  A: 

I would go with .Net Framework Capitalization Styles

PRR
A: 

There are only three types of naming in my code.

  • UPPER_CASE - Something that cannot or should not be assigned to.
  • CapitalizedSomething - A class name (and static members in those languages which have that)
  • lower_case - A variable, an instance, a function/method, parameters.

Lower camelCase is definately stupid.

Tor Valamo
I have not come across this type,all i know is camel casing and pascal casing
Ravisha
A: 

Class names, global objects, "static" constants, enums -- CamelCase

Methods, variables, arguments -- names_with_underscore

Fields -- _like_variables_with_underscore_as_prefix

macias
It depends on the languae used,most og cased underscore is disouraged esp in C#
Ravisha
Yes, it is true, this is from C++ mainly and that is why I dislike C# just a bit for forcing different convention ;-)
macias
A: 

Whilst I have my own preferences, in code that extends a particular library, I attempt to match that library's naming conventions.

P-Nuts
A: 

The worst naming convention I have found ever is Symbian C++. It may take multiple indices to cover in full.

Xolve
+3  A: 

I'm not a fan of non-descriptive names or Hungarian style "name it after what the language already says it is," but I give most iterators three or four character names ending with it.

for ( vector<Dog>::iterator kit = kennel.begin(); kit != kennel.end(); ++ kit )

The name is terribly non-descriptive, but it unambiguously indexes/refers to a descriptive container name (kennel) which is right there in plain sight, since iterators have such small scope. It is useful to know I'm iterating using an iterator and not an index when glancing at the code. (An index would be named kx, pointer kp, but those are less common.)

Beats using i and j indiscriminately for all loops, anyway :v) .

Potatoswatter
Re: Hungarian Notation, Joel had a convincing writeup at http://www.joelonsoftware.com/articles/Wrong.html arguing that the idea has been pretty well misrepresented. The basic idea he describes underlying the notation (to disambiguate variable usage when its type is insufficient to do so) is one that I consider extremely reasonable.
Aidan Cully
@aidan: that's another whole argument. Trying to clarify what a variable's type cannot do can be a bad idea in C++ when you might change/extend the variable's type, and then you have to rename it. The beginning of the name isn't the best place for implementation details, especially when automatic completion works with the beginning. My rule is to put the most general identifying information first, and type info (for example, if I cast info from one variable to another) at the very end.
Potatoswatter
+6  A: 

The most important thing is to have a naming convention, which is uniform in your project and actively used.

It's also a question of tools - for example, if your IDE gives different colors/fonts to different constructs, then you don't need to reflect it in your naming conventions.

For Java, the most widely accepted coding style is the one by Sun. To summarize:

  • Favor long, descriptive names over abbreviations.
  • All caps for statics, camel-case for everything else.
  • Class names (including interfaces, annotations, enums) start with uppercase; method and variable names start with lowercase.
Eli Acherkan
A: 

I think use and dependence on ANY naming convention is almost dumb in HIGH level languages, especially languages that are well provisioned for by development environment.

For example Visual Studio conveys far MORE information by simply hovering over the variable in question and reading the popup, extended information by right clicking, Go To Definition, Find All References, re-factor etc. - I assume its similar in other environments.

Also most naming conventions obsess about the type of the object, the name of your objects should explain the INTENT/PURPOSE of the object.

Another huge problem with strict naming conventions is the dev could make a mistake in naming the object, so when another dev picks up the code, reading the name of the variable is useless - much better to rely on the IDE's tools:

XML comments are far more useful then any naming convention.

    /// <summary>
    /// number of ducks in formation 
    /// </summary>
    int v = 10;
Adrian
-1 because I think that using a naming convention (it doesn't matter much which) contribute to make your code more tidy and readable, and lets you get at glance some information about the variables/methods/... used even without using an IDE; +1 for the ducks :D
Matteo Italia
BTW, look what happens when you don't choose a naming convention: you get the PHP library. :P
Matteo Italia
Adrian, with all due respect, you need to read Robert C Martin's "Clean Code"
Elliot
-1, variables like these make your code very hard to read. Let's say: int l = v * (2 / s * a). Size of the lake = number of ducks * (2 / season constant * average duck size. Good luck waiting for Visual Studio's tooltips :)
Zyphrax
I was trying to say that tidy code with clear names that aim to depict the purpose of the field/object are better then one state the type. In most cases the compiler doesn't care what you call them.
Adrian
+6  A: 

I just stick with the conventions used by the library of the language I'm using.

Joe Gauterin
What about projects that span different languages? Does the language library style always override the API library style?
Potatoswatter
+1  A: 

I like Pascal case like this where member variables start with m_ and function arguments start with _. Looks like this:

class Foo{
    private String m_MyString;

    public int Bar(int _input){
        int output = _input + 3;
        return output;
    }
}
wheaties
+2  A: 

I as being a Java developer just follow the Naming Conventions of the Sun Java Code Conventions.

I am inclined to apply exactly the same in PHP, but I mostly just replace Java's camelcase-separation by underscore-separation and keep the remnant the same so that's nicely laid out with the core PHP functions (which in turn already use the underscore-separation).

No wording about C/C++ as I don't do it, but if it was me -and if there is any-, I would just adhere Microsoft's own Code Conventions on that area.

BalusC
+4  A: 

English.

It sounds bloody obvious, but naming conventions are intended to make code more readable. The use of non-English terms is the most effective way to destroy readability; its use can instantaneously exclude 90-95% of the developers in the world.

In comparison to the single rule "Use English", all talk about about uppercase, lowercase, abbreviations, underscores, prefixes or suffixes, etc is wasted effort.

MSalters
English as opposed to French or as opposed to trademarks or jargon?
Potatoswatter
Jargon (def: the language used by a professional class) is not a problem. Referring to your own trademarks usually isn't either, e.g. in a comment "This class is the adapter for the Foo interface of our XYZ (TM) app.
MSalters
A: 

I've found that the best approach on projects with more than one developer is to be consistent. Use whatever standard is already in use, even if you don't like 100% of it. If you have a reason to change, you must be prepared to change the whole code base, therefore you must have a very good argument for doing it (unlikely, to be honest.)

Other than that I tend to use Frank Sutter's recommendations (see Exceptional C++ et al.) although I don't get precious about it; too much time, effort and money is wasted on arguments over coding standards and naming conventions IMHO and it's too easy to find yourself getting wound up about it. Life's too short.

Robin Welch
A: 

Consistency is paramount. Actual practice doesn't matter at all as long as the code is legible. I have OCD and I get uncomfortable if my source isn't formatted consistently, but my preferences for the particulars have changed over time. Underscores used to be a problem for me, but I changed my keyboard layout a long time ago to use ~!@#$%^&*()_={}" as the non-shift characters so I can type C++ code as fast as or faster than regular discourse. Embedding type information in an identifier is a good way to make extra unnecessary work for yourself. In a strongly-typed language, the type is already known, and in a weakly-typed language, the type doesn't matter.

Anyway, following is my current style.

Variables, member variables, functions, and member functions use lowercase_with_underscores.

int local_name;
int member_name;
int function_name();
int method_name() const;

Get and set accessors have the same name.

const Type& value() const;
void value(const Type&);

Typically, though, I use a templated meta-accessor from my box of tricks:

joop::accessor<Type> value;

Types are in CamelCase.

class ClassName;
typedef int TypedefName;
enum EnumName;

Unless they represent STL-like template classes, as is the case with my personal joop library.

Constants use UPPERCASE_WITH_UNDERSCORES.

static const int CONST_MEMBER;
ENUM_MEMBER = 0
#define REPLACEMENT

Template and macro parameters use single uppercase letters or follow another appropriate convention for legibility.

#define MACRO(A,B,C)
template<class T>
template<class Category, unsigned int size>

Namespaces use heavily abbreviated, all-lowercase, all-alphabetic names.

namespace ns { ... }

Local identifiers have a length roughly proportional to the size of their scope. I don't use global variables.

Jon Purdy
A: 

I avoid systems that rely on complex and obscure abbreviations, like Hungarian notation. I always find this more confusing than helpful. Maybe if you got used to it you could read the prefixes quickly and immediately glean bunches of information, but even if you and I learned it that well, the chances are that other members of the team would not.

I particularly dislike Systems Hungarian where there is a prefix to indicate data type. Primitive data types are usually obvious from context: If I write "x=y+4", it's pretty obvious that x and y must be numbers, probably integers. Furthermore, an informative name should make the data type obvious: I expect "quantityOrdered" to be an integer and "customerFirstName" to be a String and not the other way around. If this is not true, the variable names are misleading and should be changed. Like, if "customerFirstName" is really a hash value of the customer name, then call it "customerFirstNameHash".

My one exception to this is when I have the same value with multiple data types, like if I'm reading an HTML form so I get a number in as a string and then convert it to an int. This almost always means a string and a "natural type", so I prefix the string variable with "s", like "sBirthDate" and "birthDate". I've had a few cases where I had a date as a long and also as a Date, in which case I've prefixed the long version with "l", like "lBirthDate" and "birthDate".

I have mixed feelings about Apps Hungarian where you use prefixes to indicate the semantic meaning of the data. While I don't use "real" Apps Hungarian myself, I often use some simple conventions like:

Indexes into an array or other "current number" are prefixed with "x". Counts of the number of something are prefixed with "k". A structure name is plural. The current element being worked is singular.

So for example, if I have an array of employees I'd write code like this:

Employee[] employees=buildEmployeeArray();
int kEmployee=employees.length;
for (int xEmployee=0; xEmployee<kEmployee; ++xEmployee)
{
  Employee employee=employees[xEmployee];
  ... process ...
}

Of course this convention isn't limited to arrays, it works in any context where you have a structure with individual elements, counts of things, etc.

I often find myself having a key or other identifier that I'm looking for and the one I'm currently working, so I prefix these with "want" and "got" respectively, like "wantCustomerId" and "gotCustomerId".

Similarly, when processing through a list I often have a previous value and a current value of some identifier, so I prefix these with "prev" and "curr", like "prevCustomerId" and "currCustomerId".

That's about the only common cases I can think of.

I have a few "never ever do this" rules.

  1. DO NOT use generic names like "x" or "num". There are only two exceptions to this: (a) Variables used for an extremely short span of code, like an index in a 3-line loop. (b) Generic functions. Like, if you have a function that adds a number of days to a date, sure, you can call the variable "date" because it could be the date of anything. I used to work with a guy who regularly named all his integer variables n1, n2, etc, and all his string variables s1, s2, etc. Reading his code was a nightmare, full of lines like "n4=(n5-n9)*n3". I finally concluded that the only way to maintain his programs was to first go through and figure out what all the variables were and rename them to something meaningful.

  2. DO NOT re-use variables for different data. If you have a function that, say, gets the sale amount and does some processing on it, then gets the tax amount and does some processing, then gets the payment amount and does some processing, create three fields, e.g. "saleAmount", "taxAmount", and "payAmount". Don't use a single variable "amount" for all three. Modern computers have enough memory that creating a few extra variables is not going to use it up. The gain in readability far exceeds the trivial value of the "saved memory".

  3. DO NOT use inconsistent abbreviations. If you want to abbreviate quantity as "qty", fine, I can probably figure that out. But don't use "saleQty" over here and "stockQnty" over there and "orderQuant" some place else. Pick one abbreviation and stick with it.]

  4. If two variables are similar, DO NOT distinguish them with numbers or deliberate mis-spellings. If you have, say, a sale total and a refund total, DO NOT call them "total1" and "total2", or worse, "total" and "totl". I have seen this done so many times it makes me want to throw up. Give them names that give us a clue how they are different, like "saleTotal" and "refundTotal".

Jay
A: 

I don't believe there is single naming which covers whole area. And there is no option to choose. If the reason of considering naming convention is code compatibility (which helps easier understanding), this is not a problem of favorite. Naming which recommended and used in specific language or base-framework should be used. Whatever, and if you like or hate it. Because it guarantees best compatibility.

So, well-designed languages treats naming as part of language design or a basic guidance. We can find them in it's official documentation. And some languages fixes naming as a part of syntax. See Google's Go language. It uses upper/lowercase to present member's access modifier. (Pascal for public, camel for private) This is under development, but it means a lot.

Additionally, most languages does not recommend using of underscore('_'). Because it means something special cases like 'hidden', 'internal use only', 'hack', 'temporary' or 'debug'. Of course, this is case by case, and depends on the languages.

We have free to use anything we want, but other programmers will hate code written with own, creative special naming conventions.

Eonil
+1  A: 

I think you should follow the formal conventions for concrete language. For example, here are the naming conventions for Java language specified by Sun: http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html

By following standarts you will make your code well readable everywhere by everyone.

Andriy Sholokh
I generally agree, but I think standards like this can become out of date. One example I am thinking of is having CONSTANTS_NAMED_LIKE_THIS in Java. Syntax colouring has done away with the need for such a bold naming scheme for these variables and there are alternatives that can be used in conjunction with syntax colouring which are much more friendly on developers' eyes.
David