I am wondering what is actually the preferred way of naming variables: some_variable or somevariable.
Looking at some libraries, I have seen both. What is more, some wide-spread style conventions like Google C++ Style Guide allow both.
What do you prefer and why? Is there a rule or good practice which tells when to use which? And does the same applies to argument names in functions/methods?
And is mixing those two conventions a good idea? If yes, when should the first naming conventions be used, and when the second one?
Use what's most readable and least confusing.
You should follow whatever naming convention makes sense to you.
For me, I always use camelCase for variables and PascalCase for public methods and properties.
The C++ standard libraries use both conventions for function and class names, though the _ convention is apparently gaining popularity (it's used in most recent additions, since the STL got standardized). Stick with your project guidelines, or make up your own, but apply them consistently.
My personal style is to use some_function for functions, somevar for variables, PascalCase for class names. I don't have a copy of The C++ Programming Language by Stroustrup around, but I believe this is his style as well.
Related
I just dived into the world of using dispatch_queue a little bit more intensively and was wondering if there are some naming conventions that should be used just for GCD objects, so that the code of the classes is then more easily divided into GCD and other Code.
Or could it be that it is a bad idea to have separate naming conventions for GCD?
I'd suggest to simply stick to the usual Cocoa and CoreFoundation naming conventions. Extend them as needed.
Edit after comments:
First of all, you shouldn't start variables with an underscore as this is reserved for Apple. Instead, I recommend to postfix with underscore, like someVariable_ or prefix with something else (for example, a colleague of mine uses i_ for instance variables and g_ for globals).
Whether you want to add some kind of polish notation (like prefixing with q_ for queues) is entirely up to you, it's a matter of taste. I think it's more important that you can recognize what a variable is used for, like imageProcessingQueue_ instead of just queue_.
The problem is that this is entirely subjective and cannot be answered in an "this is the ultimate truth" way. Common sense and forethought are important and laziness (abbreviated names or very generic terms like simply queue_) should be avoided.
If I am naming a new class in an OOP language, which is a better convention:
XMLWriter
Most common
XMLwriter
Easier to distinguish
XmlWriter
No longer an acronym
XML_Writer
Removes the point of camel case
Pedantic yes, but I'm curious who uses what and why.
Java conventions seem lately to favor treating well-known acronyms like words, so: "XmlWriter"...
http://www.ibm.com/developerworks/library/ws-tip-namingconv.html
Java Naming Convention with Acronyms <-dupe question?
http://geosoft.no/development/javastyle.html
But nobody seems to be very consistent. Take JavaScript's XMLHttpRequest for example. What a trainwreck!
I'm pretty sure all the different naming convention people will want to string me up for saying this. But in my opinion the naming convention you should use should be the one that is easiest to read. Names are only used by humans, so therefore they should be whatever is easiest to read/understand. So for things like XMLWriter, I would probably put it as XmlWriter since that seems a little easier to read. For things that are very very common (i.e. XML) I think treating it as a word works best. If you have some acronym that is specific to your domain, then I might capitalize it so that people who don't use it all the time would understand that it's an acronym. Basically make it easier to understand the names real intention even if it makes it slightly harder to read. I think using common sense and best judgment is better than trying to stick to a absolute set of rules in naming. Although the naming should try it's best to follow a reasonable set of naming conventions.
I would say you should always prefer the most readable one (as zipper said) and atleast start the class name with capital letter as somewhere i read that its a Java standard convention and I also feel that starting with a capital letter always makes you sure that its a Java class.
What are some recommended best practices to follow when naming variables? Global variables?
When working with a solution having many projects, insure that all public names indicate a relevant context. Do not use identical names in different projects. Compilation works but maintenance can be a nightmare.
To a large extent it does not matter what standards you decide to adopt. The most important factor is that you stick to it! Consistency is really important and as long as you manage that your code will be significantly easier to read and maintain in the future.
As one idea you could check out the hungarian notation used for Win32 and C++ programming under windows.
Notation Definition (PDF)
Keep your names meaningful, the code should self document, avoid abbreviations the length of the name isn't usually a problem in most languages.
Boolean variables should begin is* or has*, try to choose a name that avoids requiring negation in tests as the ! can often be missed.
Group variables associated with an item by using a common prefix i.e. documentTitle, documentType, documentSize etc.
Avoid using numbers to distinguish variables unless an index is involved.
Forget about Hungarian notation.
Some broad strokes:
Use i, j, k for loop variables. It's very common practice and easy to understand.
For boolean (true/false) variables, use predicate names like isDirectory or canExecute.
Whether you camelCase or use_underscores is just a matter of preference.
It may be a good idea to decorate variables with Hungarian notation describing the meaning of the variable, e.g. iMax could be the index of the maximum element in an array. It's less useful to decorate names with the language-level type information. For a very entertaining explanation of the difference, and why one is good and the other bad, see Joel's essay.
Best to not start them with numbers or symbols in some languages. Also, don't use reserved functions of the language you're using. For example: in C# you wouldn't want to name it "if", "else", "void" "try" etc...
I'm by no means an experienced programmer, but I've somewhat had it drilled into me at college and uni, and have seen it on sites like this, that when naming variables they should mean something.
Maybe this is an education thing, but it does make sense - the variable name should make it easily apparent what that variable is used for, anywhere in your code. It comes down to, I think, the fact that code shouldn't need masses of comments - it should explain itself. Variable naming is a part of that.
This question is about variable naming style in objective c and cocoa. I just want to stress that I'm not looking for a "right" answer, just good ideas.
I've read through Apple and Google's objective c style guides and I'm not really happy with either of them. Apple's guide doesn't have any real style recommendations regarding instance variables vs local variables. In fact, the Cocoa library itself seems perfectly happy having function parameters of the exact same name as instance variables. That makes me cringe personally.
Googles guide specifies that instance variables should be indicated with a trailing underscore. Alright, all well and good, but it suggests that we then synthesize every public property with #synthesize property = property_. I don't know about anyone else, but I'll be damned if I'm going to do that for every instance variable in my project. I think it's a wasteful and confusing solution.
I'm tempted to go with the myX (eg "myInstanceVariable") naming style for object properties, but I have rarely seen that style in objective c.
So yeah, what do you use? Any style conventions out there I don't know about that you've found useful? Do you think function parameters with the same name as instance variables is dangerous, especially in multiple developer environments? Thanks guys and gals!
NOTE - As many people have pointed out, my terminology was off in the OP. Apologies if the original wording hurt the clarity, but I think the point was still clear.
I tend to use non-prefixed instance variable names (note that "member variable" is a C++ism as it's suggestive of structures and classes being mainly interchangeable, which is not the case in Objective-C), and in cases where ambiguity arises, I use the Smalltalk convention of naming the parameter by its type with "a" or "an", e.g.:
- (void)setFoo:(SOFoo *)aFoo;
{
foo = aFoo;
}
(of course, in modern ObjC you'd use a property for this.)
Using theFoo instead of aFoo is also somewhat common; see the answers to this question.
The Google convention makes sense if you're really worried about conflicts. If you use an Xcode text macro or tool like Completion Dictionary or Accessorizer to generate your directives, it's pretty simple to adopt.
Note that the Cocoa key-value coding guidelines pretty much assume either (a) you do not prefix/suffix your instance variable names, or (b) you implement (or synthesize) non-prefixed/suffixed accessors for them. As someone else mentioned, do not use the _ prefix; it's reserved for Apple's use in their frameworks.
First: there are no "member variables" in Objective-C, there are "Instance Variables" or "ivars".
Google is NOT any kind of authority on Objective-C coding or Mac development. Google Earth is a Qt app: 'nuff said.
I seem to remember seeing an official coding style guide from Apple for Objective-C, which I'm not finding at the moment. This article is a pretty good summary, though:
http://cocoadevcentral.com/articles/000082.php
Found it! Here's Apple's official coding guidelines for Cocoa:
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html
In Cocoa, the style is to have pascalCased (or is that camelCased? I can never remember) names; and have the member variables be named the same as the accessor methods. (Such as NSInteger anInteger, - anInteger and - setAnInteger:).
It might not be the best style, but it's probably a good idea to get used to it if you are going to do any amount of work with Cocoa, as a number of mechanisms assume this particular kind of naming convention.
_foo is not bad habit. Or at least it is not anymore. See:
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingIvarsAndTypes.html
m_variableName is pretty common too for member variables.
Personally, most of the time, I just go with the same name for both variables and making the distinction between this.varname and varname.
I'm currently in University and they're pretty particular about following their standards.
They've told me this:
All classes must start with a capital
letter
Correct
public class MyClass {}
Incorrect
public class myClass {}
public class _myClass {}
All methods must start with a
lowercase letter
Correct
public void doSomething() {}
Incorrect
public void DoSomething() {}
public void _doSomething() {}
all variables must start with a
lowercase letter
Correct
string myString;
Incorrect
string MyString;
string _myString;
Yet in my last year of programming, I've been finding that people are using much different rules. It wouldn't matter if it were just a few people using the different rules, but almost everywhere I see these different practices being used.
So I just wanted to know what the reasoning behind the above standards is and why some of these other standards are being used: (are they wrong/old standards?)
Most methods I've seen start with a capital letter rather than a lowercase-- Pretty much any of Microsoft's methods I've been using from their imported namespaces. This is probably the most common one I've seen that I don't understand
A lot of people use _ for class variables.
I've seen capitals on variables ie. string MyString;
I know I've missed a few as well, if you can think of any that you could add in and give an explanation for that would be helpful. I know everyone develops their own coding styles, but many of these practices have reasons behind them and I would rather stick with what makes the most sense.
Thanks,
Matt
There is no valuable reason to choose one coding style rather than an other one.
The most important thing is to agree on a coding style with the people you are working on. And to help you to all agree on a coding style, your professor told you a coding style.
Most of the time, it is just a point of view. So, just follow your professor's coding style if you have to code with the university....
standards are arbitrary, like which side of the road to drive on; just do it like they tell you to do it ;-)
Most people are talking about naming convention style, but there are other things to consider when approaching naming conventions, such as what you actually name a routine.
Routine (methods, functions, and procedures) names should typically by in the form of a strong verb + object, regardless of how you format it. For example:
paginateResponse()
or
empty_input_buffer()
as (respectively) opposed to
dealWithResponse()
or
process_input_buffer()
Both "dealWith" and "process" are verbs, but they are ambiguous and cause any other programmers working with your code in the future to have to consult the actual routine definition to determine what it really does.
"Strong" verbs, on the other hand, as shown in the first two examples, are much more powerful in their descriptive power and really pin down what the routine is doing.
This makes your code easier to read as it is self-documenting and leads to higher levels of cohesion.
Also, as a personal point of style, I try to avoid at all costs using "my" in any name.
Standards are only standards if they are followed, and every company or institution has their own standards. It is one of the worst parts of programming. :D
Speaking specifically about the leading _. From my experience this is mostly used on variables that are declared private within a class. They are usually coupled with a method to retrieve them that has the same name without the leading _.
I am trying to follow the rules from Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries by Krzysztof Cwalina and Brad Abrams
Guidelines in this book are presented in four major forms: Do, Consider, Avoid, and Do not. These directives help focus attention on practices that should always be used, those that should generally be used, those that should rarely be used, and those that should never be used. Every guideline includes a discussion of its applicability, and most include a code example to help illuminate the dialogue.
Also, you can use FxCop to check your compliance with those rules.
Standards help with readability, and therefore improve maintainability. (because when you can read the code faster, easier and more accurately, you can debug and repair it, or enhance it, in less time and with less effort.)
They have no effect on reliability or availability, cause the computer doesn't care what the variables are named or how the souurce code is formatted.
If you code is well-organized and readable, you have achieved the objective, regardless of whether or not it conforms exactly to anyone elses "standard".
This says nothing, of course, about how to handle the environment where "standards" are high on someone's list of developer evaluation tools, or management metrics...
I see logic behind capitalisation of classes and variables; it means you can do things like
Banana banana; // Makes a new Banana called banana
I've been learning Qt recently, and they follow your conventions to the letter. I wouldn't ever follow Microsoft's naming conventions!
The standards I've seen echo what's in the Framework Design Guidelines. In the examples you've stated above, I don't see you distinguishing between visibility (public/private).
For example:
Public facing methods should be PascalCase: public void MyMethod() ...
Parameters to methods should be camelCase: public void MyMethod(string myParameter) ...
Fields which should always be private, should be camelCase. Some prefer the underscore prefix (i do) to distinguish it from method parameters.
The best bet on standards is to have your team agree upon conventions up front when the project kicks off, you'll find everything much more consistent.
Coding styles are based on personal preferences and to a large extent the features of the language that you're using.
My personal take is that it's more important to be consistent with a convention than picking the "right one". People can be dogmatic about they're preferred style and things can often delve into a religious war.
All classes must start with a capital letter - This goes hand-in-hand with variable naming and helps prevent confusion that would arise if you had both classes and variables named with the same rules. My preference is a capital letter because I'm used to it and it follows the guidelines for my preferred language (C#).
All methods must start with a lowercase letter - same goes, although I start my methods with an uppercase character (as per C# guidelines).
All variables must start with a lowercase letter - this, I believe, is dependent on you language's scoping features. Often people prefix variables (usually an underscore or a character like "g") to indicate a variable's scope ("g" might mean "global"). This can help prevent confusion where variables have the same names in different scopes. My C# driven preference: all variables have start with a lowercase letter and I use "this." to reference a global variable of the same name where scope is a problem (this usually only occurs in a class's constructor).
I can't let 3. go by without mentioning Hungarian notation (which is grossly misused and misunderstood). Joel has a great article that helped me understand these better.
In addition to the main point, that while any specific standard is essentially arbitrary but it's important to have some agreed upon standard, I'd also add that some standards are ubiquitous enough to have achieved the status of the "correct" way to do things.
For example, in java, class names in professional code are always in CamelCase. I'll qualify the always in saying that your code will compile if you break the standard, and you may occasionally find some open source projects that break the convention as well, but I believe that most people would take that as a sign that the author is not too familiar with the language. Most of your professors guidelines are fairly standard (for java, in any case). Being radically different in this case, apart from annoying your professor, will probably irritate total strangers ;)
It's interesting to me that some languages seem to have taken this standardization to heart, and enforce capitalization to have specific meaning (e.g. Haskell).
The rules you're citing are those used pretty universally in the Java world.
Are you doing Java code at university? If not, it may be that they were previously teaching Java, then switched to C# but kept the naming conventions.