10

I always struggle in abbreviating variable names. Is there any standard for abbreviating variable names?

8
  • 1
    Is this a duplicate of stackoverflow.com/questions/4358840/…?
    – user7043
    Apr 29, 2011 at 22:44
  • 13
    Take the hint. If it's difficult, then stop doing it.
    – S.Lott
    Apr 29, 2011 at 23:27
  • 3
    Working with abbreviated identifiers in code you did not write causes brain damage. Apr 30, 2011 at 4:19
  • 3
    rigidly following rules is either a cause of or a sign of brain damage. Either way, the important thing is judgment. Apr 30, 2011 at 6:58
  • 1
    @T Duncan Smith: Where did that come from? You just intimated that those who agree with the accepted answer to this question have brain damage. I was just joking that I find it difficult to read cryptic code. May 1, 2011 at 2:36

8 Answers 8

70

The standard I use is to not abbreviate variable names unless the abbreviation is more readable than the full version (i for iteration indices, for instance). We name things so that we can communicate. Abbreviating variable names typically just lessens their ability to communicate.

7
  • 6
    Not sure I entirely agree. I don't abbreviate much, but I think that abbreviating in some cases is a good idea. I would find long variable names in a short local scope very annoying, actually. I write lots of functions where "p" refers to a point in 3-space. I think that that is as clear as "thePoint," and easier to read, if the function is meant to operate on a point in some fashion. Apr 30, 2011 at 5:33
  • 6
    As I said, I prefer full names "unless the abbreviation is more readable". It sounds like we actually agree. Apr 30, 2011 at 7:25
  • 1
    @Duncan, maybe that is clear to you, but not everybody would immediately see the correlation between the abbreviation and what you actually mean. I think all variables should be fully descriptive, unless you can make them immediately understandable to all other users. As Rein stated using 'i' in a loop is one such scenario where I believe it to be acceptable. May 5, 2011 at 9:56
  • 2
    I almost agree. I would say, don't abbreviate, unless the abbreviation is so common, that there is no doubt as to what is stands for. A good example is System.IO. Common could also be common just in the company that you work in. That would of course mean that new employees would not know exactly what it means. But being part of the company would mean that sooner or later they would learn the company lingo.
    – Pete
    Jun 9, 2012 at 13:03
  • 4
    @Duncan I'd quite happily get rid of anything that doesn't actually convey information in return for not abbreviating the rest. "thePoint" is a pet hate of mine in that "the" contributes precisely nothing - but it can still be made worse by abbreviating to "thePt" rather than "point" or "p". Jan 2, 2015 at 13:14
12

I'm not a C# programmer, so I can't give you much advice about C# conventions. But I do have some thoughts about abbreviations.

As I've gotten older and more experienced I've found myself abbreviating less and less. I'll admit that I was not a very good typist when I started programming. I've gotten better at that since then ;). I will abbreviate freely for variables that have very limited scope, such that I can see their entire lifetime on one screen. But other than that I prefer not to if I can avoid it- I never abbreviate to save typing.

I do still try to keep my lines under 80 chars. I'm not sure if that makes sense these days, but it is an old habit. So I will abbreviate if a variable name is otherwise going to be very long. But before I do that I will try to find a more succinct name that is equally clear- all else equal shorter is better (speaking of the expanded form.)

Where you do abbreviate it is most important, I think, that you always abbreviate the same way in a given codebase, and across related codebases. Your first instinct is likely the one to go with, as it will be easiest for you to remember, but it can be worth checking with other people on the same project. These days I work mainly with one other programmer, in an open office full of non-programmers. They think we are insane, because we often have detailed discussions about things like how to consistently abbreviate related variable names, or consistently order parameters in function calls, etc. But naming matters, even for two people. On larger teams it becomes even more important. One thing I am pretty religious about is fixing inconsistencies in things like this as soon as I spot them.

EDIT: some abbreviations are good though, I think. In my current job a lot of the code I write has to do with evaluating splines, and other parametric functions, at certain parameter values. Our codebase is in fact inconsistent in this regard. I know that u is used in some places and param (an abbreviation itself) is used in others. U is a generally understood abbreviation for parameter in this domain so I think we ought to go through and make this consistent. I would be fine with any of u, param, or parameter. We use them so much that there is unlikely to be any confusion, as long as we use just one. But I would prefer u.

It's worse than that though- we actually have several types of parameter. And we have more than one name for some of them- uggh.

The reason this got inconsistent is textbook. It turned out that we had to map between six parameter spaces- the reasons are complicated, but basically we had to have parameters that corresponded to parameter space, normalized parameter space, arc length space, normalized arc-length space, piecewise space, and normalized piecewise space. We didn't realize, at first, that we would have to map back and forth between all these spaces. And we were inconsistent in how we named parameters that describe points in those spaces.

This happens sometimes- your app grows up, and you do some inconsistent things while growing it. The important thing is that you recognize that you have gotten messy and go in and fix it before the messiness infects everything else and you wind up with a pile of rubble.

3
  • Interesting, assuming you use visual studio, I wouldn't abbreviate parameters because they'd come up as soon as you type "myfunc(" and you don't want it to say double createBox(string tb, int cir, double pmj), just a thought to add
    – Mark Lalor
    Apr 29, 2011 at 23:00
  • I mainly use emacs. I'm a bit of a dinosaur I suppose, but I also have to work with a couple of languages (at the same time, in the same code) across a number of platforms. I do sometimes abbreviate parameters if the abbreviation is obvious (and consistent,) because I try for short enough functions that I can see them all on one page, but I often don't, because I do my best to keep function signatures short anyway. The most important thing is consistency though- if "the same" parameter (conceptually) is abbreviated in one place it should always be like that. Apr 29, 2011 at 23:04
  • 1
    Anyway, the main point here, IMHO, isn't even to let you automatically type the right thing without looking it up (though that's a bonus.) The main point is to reduce cognitive burden when reading the code later. It's a cliche, but you tend to read even your own code a lot more times than you write it. If the essential ideas are essentially hard you want to eliminate as much inessential cognitive burden as you can. Consistency helps here. It's an impossible ideal, but ideal code should only contain irreducible difficulty. Apr 29, 2011 at 23:14
8

The vry rsn w dn't bbrvt s t mk sr th cd s rdbl nd mntnbl e.g.

int accountBalanceInSavings;

// could be abbreviated to
int accBalInSaving;

Note that two of the four words are shortened (account->acc and Balance->Bal), but the other two are not. What rule is applied here -abbreviate the first 2 words, it's not "words over 6 letters", because 2 7 letter ones were and one wasn't.

So could/should it be accBalInSav, yuk yuk yuk...

My experience as programmers get older and wiser, they abbreviate less and less. By my age, we are probably trying to make up for the sins of our youth though...

Keep in mind code is written once (ok, many a few more then once) and read thousands of times.

4
  • 3
    If I saw it out of context I would have no idea what accBalInSaving means. It's also the same lengthy as savingsBalance Jan 1, 2015 at 19:24
  • If one finds himself having to use a variable like accBalInSaving, then something is wrong about the design - the variable carries too much context info that actually should be implicit; if it was a property of the Account class, for example, there would be no need to put "account" in its name. And when that's the case, abbreviating is just a painkiller helping to sweep this problem under the rug. Jan 2, 2015 at 15:30
  • Is it perverse that I could actually read the abbreviated first sentence at almost a normal pace?
    – Steve
    Feb 12, 2021 at 11:16
  • Any programmer should do a course in touch typing at some point in their life.
    – gnasher729
    Feb 12, 2021 at 19:29
3

I do not believe there are any official or common rules for abbreviations. Usually a system of abbreviations is developed by each individual and within each individual project. There can be certain rules for a company's source code style policy but that as well will vary on the company basis.

On a side note, why abbreviate at all? That will result in only you understanding what the abbreviations mean. Use full and descriptive names for variables. That will lead to self-documenting code.

3

There is a similar question about single char names, Using single characters for variable names in loops/exceptions.

My answer then as now is to keep them short where the scope is small. For example, a parameter of a short function is more readable if it's short and takes less space. A class wide variable should be very descriptive.

Steve McConnell's classic book Code Complete is great for stuff like this.

2

If in doubt, spell it out.

The point of a variable name is so that the meaning of the code is clearer. Unless the abbreviation is very obvious one, then you may as well just use the smallest one possible. Variable names and function names are typically the only bits of human language in the code and so act both as 'landmarks' for the human eye to find relevant portions of code (or, in a large codebase, tools like grep or ack) and also as clues for comprehension.

When the next person comes to read your code, they will thank you for it. That person could well be you in a year's time. I have a lot of code I regret abbreviating, so nowadays I try to avoid it.

It's ok to abbreviate when...

... When the abbreviated form is used in spoken or written English by more than just the people working on your project (many dictionaries give this sort of information next to the term they define).

var extensible_markup_language_element; // don't do this
var xml_element; // better
var element; // possible if the name of the function or the documentation make it clear you're dealing with XML and not the periodic table
docs.toString(); // most people capable of reading code know docs == documentation

... When the abbreviation refers unambiguously to a single concept and would be instantly recognised by someone who is not familiar with the codebase. Even then a comment or piece of documentation helps.

var auth = user.auth;
if (auth) // If the user is authenticated?
          // If the user is authorised to do something?
          // If the authentication function exists for that user group?
          // If some setting called auth is turned on for that user?
          // If the user is the author of the document in question?
          // If the user has some authority?

var attrNames = retrieveAttrs();
if (attrNames)  // hm, attrNames sounds like an array of strings - which will be boolean true even if empty - this if looks like a bug!

const MDF // author is writing an iOS app for ordering hand-carved artisanal fibreboard so anyone familiar with the problem domain knows this has plainly nothing to do with Microsoft Database Files. Though maybe the first time it comes up in the code the author should perhaps still put its full name

... When the variable name exists only in a single scope or small function, and you do not expect the user to derive meaning from the name, use a single character. In such cases, i and j are common.

foreach $i (1..10) { say $announcement->[$i] }

... When writing an interface (i.e. not a variable name, so outside of the scope of the question, mentioned only because variable names and interfaces which set them often use the same vocabulary) in which case other rules may apply, for instance:

some_command --transaction-message "Done" # a bit wordy - keep, but ALSO allow for convenience:
some_command --msg "Done" # might be useful
some_command -m "Done"    # if you can spare -m

... When your codebase needs to refer to the same concept many times in the same project and when the abbreviation can be defined in a style guide for that project, and when it is unambiguous. If your project is not big enough for a style guide then it's not big enough for it to be worth it.

I'm not going to provide a code example to this one because by definition it only works in a large project, but see also the next item:

... When working on an established project which has had multiple contributors and a style guide which mandates abbreviations. In which case, abbreviate only as per the style guide, but look out for problems and be prepared to annotate with comments (like "this is a list of attribute names as strings").

Types should end in “_t” ; Raw struct definitions in “_struct”

- https://metacpan.org/source/SHLOMIF/XML-LibXML-2.0117/HACKING.txt

One final thought: if you still have unacceptably long variable names (e.g. composed of four or more semantic units like totalAfterTaxInLocalCurrency), it could be a symptom that your code is trying to do too much in a single scope and its functions need to be refactored out or your variables might be more logically managed in a single object.

0

The reason we abbreviate variables is to stop typing large variables, but at the same hand the abbreviated variable should be explicit enough that you can understand what it hold rather than going back to where it was declared or instantiated first. So for example:

int accountBalanceInSavings

--> could be abbreviated to

int accBalInSaving

---> but abbreviating it to

int accBal

Would definitely not be a good option as one would not be able to understand what the variable holds just by looking at it.

1
  • 2
    I'd mistake accBalInSaving for accumulated Bal In Savings
    – KajMagnus
    Oct 10, 2012 at 4:33
-4

You shouldn't abbreviate stuff for the sake of abbreviating stuff, you should do it for your/others convenience, but if you want to then a general rule that I have for abbreviation is if a word is more than four or five letters long then I'll shorten it to the first three significant letters of that word, e.g.:

int damagePerSecond;

could be abbreviated to

int dmgPerSec;

or if you want it a short as possible,

int dps;
1
  • 1
    This does not anything to the answers already given
    – Jan Doggen
    Jan 1, 2015 at 20:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.