Making Good Software

A blog by Alberto G (Alberto Gutierrez)

Written by Alberto Gutierrez

May 4th, 2009 at 11:54 pm

7+1 tips for naming variables

with 23 comments

1.- The variable name has to be as descriptive as possible. Don´t use generic names.

Good example: daysDateRange, flightNumber, carColor.

Bad example: days, dRange, temp, data, aux…

There are a lot of developers who would prioritize short variable names over descriptive names because that will save time when typing the code, but who cares? It doesn’t help to improve the quality of the software, it only saves a few minutes per day (maximum) per developer, by the other hand, when having descriptive variable names, the overall quality of the software will increase because it will be easier to modify and read the code.

2.- The variable name has to be as short as possible.

This rule goes hand by hand with the first rule, the variable names should be as short as possible but as descriptive as possible.

This basically means that while we still try to come up with short names, we prioritize descriptive names over short names, we only pick the shorter one when they are as descriptive as the longer one.

Bad Examples: howLonDoesItTakeToOpenTheDoor, howBigIsTheMaterial…

Good Examples: timeToOpenTheDoor, MaterialSize.

3.- It´s OK to use abbreviations, but explain the abbreviation with a comment.

Sometimes to have a good descriptive name is necessary to make very long variable names, which is fine, but the variable size can be improved by using abbreviations, just make sure that when the variable is declared there’s a comment that explains the meaning.

4.- Use proper Hungarian notation when necessary.

There’s a great post from Joel on software that explains what the proper Hungarian notation is and how to use it. Basically it says that when coding a method where we have variables holding the same data, but with different types, the Hungarian notation can help us.

Example: Imagine a method that receives apples, then it classifies the apples depending in their color, and finally discards the ones that are not matured enough. We could use in this example the following variable names:  incoming_apples, red_apples, yellow_apples, notMaturedYellow_apples, red_apples, maturedGreen_apples…

5.- Don´t use negative logic for your variable names.

Good Example:  IsEnabled.

Bad Example: IsNotEnabled.

It’s always easier to read and undertand an statement that is expressed in a positive language that in a negative language.

6.- Be consistent.

If you have used a variable name called customer in a method, then don’t call it client in the next method, or if you use an abbreviation in one method, use it for all the methods the same.

7.- Map the application domain terminology with your names.

In different domains, different concepts have very specific and different meanings, for example, “order” doesn’t always mean the same in the different domains, try to map these specific concepts with your variable names so that when you name something with a concept from the business domain it means exactly the same.

Example. If your customer just considers “order” an “order” that has been approved, don’t call “order” to a non approved one in your code, call it “nonApprovedOrder”.

Golden rule.- Spend a few minutes thinking about your variable names.

If you find yourself writing variable names as soon as you need them in your code without even thinking on their name for a second, you are probably picking bad names for them.

If you always try to have good variable names, and you have found yourself thinking a couple of minutes for the best name for a variable, even if you don’t follow the other tips, you are likely to have pretty good variable names in your code.

23 Responses to '7+1 tips for naming variables'

Subscribe to comments with RSS or TrackBack to '7+1 tips for naming variables'.

  1. Ok

    #1 – I agree with you on keeping the vars easy to read, but c’mon: daysFromDateRangeStartToEnd that is just to long. daysDateRange would be better

    #2 – go to #1

    #3,#5 totally agree

    Good article!

    Mardix

    http://www.givemebeats.net

    Mardix

    5 May 09 at 4:16 am

  2. Great list!

    I have a similar list of 5 rules of variable naming, several of which are slightly different…

    Ian Hickman

    5 May 09 at 3:06 pm

  3. Nice list. Under “Be consistent,” I’d add that you should use a consistent casing convention. Exactly what casing convention is more a matter of personal choice, but program logic can get pretty confusing if you vary between underscores, UC first, camel casing, etc. without rhyme or reason.

    Stephen Ward

    5 May 09 at 4:07 pm

  4. I have to agree with Mardix. A descriptive variable is good, but it should not consist of more than two words.

    Speed of typing is not the only argument for short variables. Speed of reading is also something you have to think about. Shorter variables means that we can keep more in our heads when reading code. It will also decrease uncertanties.

    What is the difference between

    daysFromDateRangeStartToEnd and daysFromDepartureDay. It is easy to read in this comment, but when you add lots of these variables in the code, it adds uncessessary time required to read and comprehend.

    K

    5 May 09 at 4:14 pm

  5. Hi Mardix, thanks for your comment, actaully I think you are completely right, daysDateRange would be much better than daysFromDateRangeStartToEnd, thanks for the correction!!!!

    Alberto G

    5 May 09 at 10:57 am

  6. Good points, except I don’t really like abbreviations – even with a comment it means I have to hunt for the definition to verify the meaning. Unless it is a dead obvious abbreviation, I personally stay away from them.

    #7 on the other hand is a great rule – domain knowledge is so important to a successful project, and if you (and your code) can’t speak the client’s language, then you are already starting from a disadvantage.

    Brian

    5 May 09 at 4:18 pm

  7. […] Alberto G added an interesting post on 7+1 tips for naming variables « Making Good SoftwareHere’s a small excerptIn different domains, different concepts have very specific and different meanings, for example, “order” doesn’t always mean the same in the different domains, try to map these specific concepts with your variable names so that when you name … Nice list. Under “Be consistent,” I’d add that you should use a consistent casing convention. Exactly what casing convention is more a matter of personal choice, but program logic can get pretty confusing if you vary between … […]

  8. #4 agree but in a different way. A good case for this is when parsing a numeric from a string. I.e.
    string strCustomerId = Request.Querystring[“cid”];
    int iCustomerId;
    int.TryParse(strCustomerId, out iCustomerId);
    Before this post I would suffix with type to avoid hungarian, but I like your reasoning.
    Except for the underscore in the example, id still use Camel Case

    henry erich iii

    7 May 09 at 1:58 am

  9. […] Good naming of variables, functions, classes… […]

  10. Another one: go with the language idioms. For instance, use upper and lower case like the language API. Java method: createIssue(), same method in Python: create_issue()

    ~Matt

    Matt Doar

    13 May 09 at 4:31 pm

  11. […] Pourya on May.05, 2009, under Software Development I have just read an interesting article called “7+1 tips for naming variables”. It basically describes how to choose meaningful variable names that makes scene to you and others […]

  12. I think your description and example for hungarian notation is wrong.

    The key thing about hungarian notation isn’t types it’s context.

    So in joel’s example he talks about strings that come from the user and have yet to be santised should begin with ‘us’. Strings that have been sanitised for cross site scripting attacks have the prefix ‘s’.

    So 2 strings usUsername and sUsername are the same type and most likely will have exactly the same data. However they have now some notion of context. A safe context and unsafe context.

    Another example is desktop environment that has a window Foo within in. Within Foo is another window called Bar. Bar has 4 variables that represent the XY position within Foo and within the main desktop. They are t_x, t_x, p_x, p_y. The convention would be that the t means the xy position applies to the topmost window. It also states that p means that x and y apply to the xy position in the immediate parent.

    In reality, hungarian notation is required far less in an object orientated system than it appears, misused, in most code bases.

    Ed Sykes

    4 Jun 09 at 4:51 pm

  13. […] There is nothing nicer than using some other developer code and not having to read its documentation because the names of the classes and the methods are telling us everything, so, make everyone’s life easier and take this approach, expend always a few seconds before naming any element in your code. […]

  14. […] this article: tips to write variable names, there are a few tips that can actually be applied to name any named element not only […]

  15. Hello Alberto, I’ve translated your excellent post : 7 + 1 conseils pour nommer les variables, Regards, Fabrice.

    Fabrice Aimetti

    11 Aug 09 at 3:09 am

  16. […] There is nothing nicer than using some other developer code and not having to read its documentation because the names of the classes and the methods are telling us everything, so, make everyone’s life easier and take this approach, expend always a few seconds before naming any element in your code. […]

  17. […] 7+1 tips for naming variables Tips for creating good variable names […]

  18. henry erich iii,

    In that case, I’d prefer to declare only the int variable, for the QueryString won’t be modified among these lines, or to use more descriptive names:

    int customerId;
    int.TryParse(Request.QueryString[“cid”], out customerId);

    Fernando

    31 Mar 10 at 5:04 am

  19. 5. Don´t use negative logic for your variable names.
    6. Be consistent.

    do you already see an inconsistency?:D

    a little tip:
    5. Use positive logic for your variable names instead of negative logic.

    Kot789

    5 May 10 at 12:35 pm

  20. You will be developing…but what will be next..So follow above steps..Somebody’s appreciation is better than theirs curse 😉

    Chandu

    3 Nov 10 at 4:19 am

  21. Some truly quality posts on this website, saved to fav.

    Samantha

    8 Aug 11 at 8:07 am

  22. If it is to be believed that code readability trumps all, then you would not stick to arbitrary rules such as limiting the length of a variable name.

    If saving time figuring out what something is can be seen as a good thing, then this concept extends regardless of length. An attempt should be made to make it short, but when in doubt, don’t make it too short.

    “Everything should be made as simple as possible, but not simpler.” – Albert Einstein

    RedScourge

    20 Oct 11 at 2:12 pm

Leave a Reply