Cagdas Basaraner is a software engineer graduated from Hacettepe University Computer Engineering department and Information Systems master program (Turkey). He has 5 years of professional experience, and is working on information systems with JEE web technologies. He is also a former developer of information systems with Microsoft .NET technologies and Command & Control (C4I) systems with Java technologies. Cagdas is a DZone MVB and is not an employee of DZone and has posted 23 posts at DZone. You can read more from them at their website. View Full User Profile

Best Practices for Variable and Method Naming

03.10.2012
| 16991 views |
  • submit to reddit
  1. Use short enough and long enough variable names in each scope of code. Generally length may be 1 char for loop counters, 1 word for condition/loop variables, 1-2 words for methods, 2-3 words for classes, 3-4 words for globals.
  2. Use specific names for variables, for example "value", "equals", "data", ... are not valid names for any case.
  3. Use meaningful names for variables. Variable name must define the exact explanation of its content.
  4. Don't start variables with o_, obj_, m_ etc. A variable does not need tags which states it is a variable.
  5. Obey company naming standards and write variable names consistently in application: e.g. txtUserName, lblUserName, cmbSchoolType, ... Otherwise readability will reduce and find/replace tools will be unusable.
  6. Obey programming language standards and don't use lowercase/uppercase characters inconsistently: e.g. userName, UserName, USER_NAME, m_userName, username, ...
    1.  
      • use Camel Case (aka Upper Camel Case) for classes: VelocityResponseWriter
      • use Lower Case for packages: com.company.project.ui
      • use Mixed Case (aka Lower Camel Case) for variables: studentName
      • use Upper Case for constants : MAX_PARAMETER_COUNT = 100
      • use Camel Case for enum class names and Upper Case for enum values.
      • don't use '_' anywhere except constants and enum values (which are constants).
    • For example for Java, 
  7. Don't reuse same variable name in the same class in different contexts: e.g. in method, constructor, class. So you can provide more simplicity for understandability and maintainability.
  8. Don't use same variable for different purposes in a method, conditional etc. Create a new and different named variable instead. This is also important for maintainability and readability.
  9. Don't use non-ASCII chars in variable names. Those may run on your platform but may not on others.
  10. Don't use too long variable names (e.g. 50 chars). Long names will bring ugly and hard-to-read code, also may not run on some compilers because of character limit.
  11. Decide and use one natural language for naming, e.g. using mixed English and German names will be inconsistent and unreadable.
  12. Use meaningful names for methods. The name must specify the exact action of the method and for most cases must start with a verb. (e.g. createPasswordHash)
  13. Obey company naming standards and write method names consistently in application: e.g. getTxtUserName(), getLblUserName(), isStudentApproved(), ... Otherwise readability will reduce and find/replace tools will be unusable.
  14. Obey programming language standards and don't use lowercase/uppercase characters inconsistently: e.g. getUserName, GetUserName, getusername, ...
    • For example for Java, 
      • use  Mixed Case  for method names: getStudentSchoolType 
      • use  Mixed Case  for method parameters: setSchoolName(String schoolName)
  15. Use meaningful names for method parameters, so it can documentate itself in case of no documentation.
Published at DZone with permission of Cagdas Basaraner, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Andrew Spencer replied on Sat, 2012/03/10 - 10:26am

Number 13 is an excellent suggestion - I wish teams would spend more time talking about this (actually no, that's not enough - they also need to come to agreement, and then put it into practice).

I don't entirely agree with number 11 - it depends, and I wrote a counter argument a while back, here: http://www.andrewspencer.net/2011/which-language-should-you-code-in/ 

Jean-Baptiste Nizet replied on Sat, 2012/03/10 - 11:48am

The standard Java convention is to avoid abbreviations, except when they're well-known acronyms (like URL, or HTTP). txtUserName and getTxtUserName() are terrible choices. Why not use userNameTextField and getUserNameTextField() instead?

Hussachai Purip... replied on Sat, 2012/03/10 - 7:20pm

PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails

This class is in spring security jar. It is 58 characters long.

It's under package org.springframework.security.web.authentication.preauth

which is 55 characters long. So, the FQCN is 55+58 = 113 characters long !!!!

Liam Knox replied on Sat, 2012/03/10 - 7:48pm in response to: Hussachai Puripunpinyo

But you know what it is right?  Which is the main point

Hussachai Purip... replied on Sat, 2012/03/10 - 9:51pm in response to: Liam Knox

I just wanted to show the fact of the longest class in spring security and it far exceeds 2-3 words that is recommended by number 1. I don't have any problem with a very long class. I know that naming a class is not easy and I have no idea to name it a better one.Actually, I like it because it follows the convention of spring naming convention that tends to be long and clear. One thing that I don't like about long class name is it is not my preference. BTW, my preference is minor point.
IMO, breaking a standard naming convention is not a bad idea but breaking a naming convention that is already existing and is used widely in the team is extremely bad idea.

Lund Wolfe replied on Sun, 2012/03/11 - 12:05am

Totally disagree with #1.  Use a meaningful name for variables, loop variables, methods, classes.  Don't be stingy.  Use enough words to be fully descriptive.

Liam Knox replied on Sun, 2012/03/11 - 3:37am in response to: Hussachai Puripunpinyo

Agreed, #1 is not correct. That you know what is being represented is more important than any arbitrary limit on words/characters etc. And I agree having a consistent conventionfor a team, or I would say more appropriatedly within a give project is also important.

Java standards seem a good starting pointing as obviously they have been adopted by many and are pretty sensible

 

Cagdas Basaraner replied on Wed, 2012/03/14 - 10:55am in response to: Lund Wolfe

#1 includes "short enough", "long enough", "generally" and "may be" statements. It is not a strict rule. It's just a general suggestion for avoiding codes full of too short, too long and vague variables. Fully descriptive naming is very important and explained on following items.

Thanks for the comments. 

Developer Dude replied on Mon, 2012/03/26 - 7:31pm

1) Don't shorten names by one or two vowels - i.e., lbl versus label. It reduces readbility and gains very little if anything.

2) Consistency is good, but only if everybody is is consistent also. Beyond that, if everybody else is consistently bad in naming and inconsistent in their naming conventions, then using a different format that is simpler and consistent within itself may not be a bad thing and may improve the code.

3) I only add words to vars that add value. As mentioned I don't necessarily need to know the type of a var - not even that it is a label v. a field. I really don't need to know (or want to know) that a var is a HashMap - in fact at most I want to know its interface, not its implementation (e.g., don't do this; customerHashMap - use customerMap if you have to say it is a Map, and pass it around as a Map, not as a HashMap)

I totally disagree with one or two char vars - almost any loop benefits from knowing what the counters and indices are in adding understanding to what it is doing and why. I almost always use words.

I do use underscores for class member vars and arguments. Class member vars get a leading underscore and args/params get a trailing underscore. Even though an IDE can color code and format each, I find it still helps them stand out in the code, and more than once this practice has either prevented a bug, or pointed one out.

Finally, as important as naming conventions/practices are, the most perfectly named var can become the worst if it is not kept up to date; I have seen a lot of var names become very confusing because during a refactoring someone was too lazy to rename them. Ditto with method names - even more so in fact.

Developer Dude replied on Mon, 2012/03/26 - 7:41pm

Also, keep your interfaces simple and consistent.

I've seen "fetch", "get", "retrieve", "search", "pull", "pop", "read", etc. for getting some value from some data store (whether it is a DB or an in memory array or a file). I've seen "put", "persist", "set", "push", "add", "insert", "update", "write", etc. for putting a value into a data store. I've seen them used all mixed up in the same class and across different classes/interfaces without any kind of rhyme or reason

I prefer to use CRUD (Create, Read, Update, Delete) and only those. I do not add what I am Creating to the method name - it should be obvious from the context (either the argument/param or the class containing the method). I also try to not state whether the data store is a DB, or a file, XML, or an in memory cache or what - I call it a "Data Store", and if the actual persistence mechanism changes then it doesn't matter to the caller - it shouldn't matter to the caller.

Timothy Bauden replied on Thu, 2014/05/15 - 3:59am

Guide # 5 is also important, for every business you have the right business naming. This will be the key in knowing your product, your company and you as owner. There are many business have failed because they haven't think of the unique name for their company or business. Various guides are offered online when it comes to business branding and one of the guide that I have tried is the "Business Start Up" books created by Alexandra Watkins, this was also featured at Amazon but you can see it directly at eatmywords.com just check link to know about the tips.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.