80

I am having a problem in understanding how to apply camelCase syntax to some of my variable names.

For example, how should I correctly write a word like "phonenumber" in camel case? Is it phoneNumber or phonenumber? Similarly with "username", is it username or userName?

I think it doesn't look right with camel case like motorCycle, passWord, sunDay, setUp or waveLength since these are just one word each. I think that could be why it's called hashMap but also hashtable in camel case without the capital in the last case because hashtable is one word while hash map is two words.

But if the motorcycle has a color then would it be motorcycleColor since a word is concatenated? Is that correct or should it be phoneNUmber, waveLength, sunBlock and even sunDay for the Sunday of the week?

Why for instance is the method called getISOCountries while it says HttpHeaders e.g. it's not clear what becomes lowercase if we have a method like String camelCaseString = dog.toCamelCase() or interface CamelCase.

Related: https://english.stackexchange.com/questions/889/when-should-compound-words-be-written-as-one-word-with-hyphens-or-with-spaces

Niklas Rosencrantz
  • 8,008
  • 17
  • 56
  • 95
  • 2
    Great question, I always asked myself how to write "fileName" (and the wrong "filename"). I think this word is written differently from programmer to programmer... – Ray Feb 25 '14 at 12:29
  • 3
    @PacMani You might enjoy the discussion [here](http://english.stackexchange.com/questions/5366/which-is-correct-filename-file-name-or-filename)! – Jason C Feb 25 '14 at 12:57
  • 1
    Closed as opinion based because Code Complete is primarily opinion based. Aren't there any Bell Labs studies from the 70's someone can cite to prove that people are going to write 40% more bugs if you camelcase userName? – Peter Turner Feb 25 '14 at 15:19
  • 1
    I tend to think that the definition of camel case is mostly unambiguous though, and this is just asking about the definition. – Panzercrisis Feb 25 '14 at 16:26
  • 4
    @909Niklas I'd drop "name" entirely as much as possible. Just use "street" If it's a string, it's a name unless that's detrimental or confusing. `username` is what it is, it's a call sign, not the "user's name", so it's more like motorcycle than firstName or lastName (which should be camelcased) – Peter Turner Feb 25 '14 at 17:56
  • 8
    For cases where it's really hard for you to tell if a two-word phrase is a compound word, pick a capitalization and stick with it. As with most coding conventions, being consistent within a single project is what's most important. – Kevin Feb 25 '14 at 03:21
  • 2
    @PeterTurner Some programmers would say that `street` should be a class and `name` one of its attributes/data members. – JAB Feb 25 '14 at 20:04
  • 1
    @909Niklas I totally agree with PeterTurner. Without that name, you cannot know it's a string which is meant, not an instance of a class. In Blitz3D, this became a nasty issue when handling files, because the parameters where called "file", but not a file handle was meant rather than the path to the file, and in some functions it was not. – Ray Feb 25 '14 at 21:39
  • 1
    At the moment answerers carefully omit non-obvious and controversial cases like "username", "setup", "filename" or "filepath" – default locale Feb 26 '14 at 04:01
  • 2
    Is there a bikeshedding tag? It's funny that questions like this always end up in the newsletter because everyone has an opinion, not necessarily because it's a good or interesting question. – pgraham Feb 27 '14 at 15:15
  • 2
    phonenumber is not a word. It's two words, so that would be phoneNumber. – Mark Freedman Feb 27 '14 at 20:09
  • 2
    it should always be `bikeShed`, never `bikeshed` – Martijn Nov 10 '14 at 13:20
  • 2
    @defaultlocale As for `filename` I've seen both `filename` and `fileName` and personally I think `filename` looks the best. For example, "Web site" and "e-mail" are both so common in popular culture that they are now written as one word instead of two. Very common words in computer programming should logically do the same thing. `filename`, `hashmap`, `username`, `password`, `testcase` etc. are all so common that they look quite a lot more beautiful as one word. camelCase just makes them look weird. – Brandin Feb 26 '15 at 11:02

7 Answers7

177

You should capitalize the letter after where there would "normally" be a space (when you would write a letter instead of sourcecode). Your first assumption is correct:

  • It's a "motorcycle", not a "motor cycle", so your variable should be named motorcycle, not motorCycle.
  • It's a "hash map", so you go with hashMap, not hashmap.
  • "Sunday" is one word -> sunday, not sunDay.
  • While "day of week" would be dayOfWeek, not dayofweek.
Jack
  • 4,449
  • 2
  • 26
  • 30
oezi
  • 1,931
  • 1
  • 12
  • 10
  • 5
    For what it's worth, my team and I generally use `hashmap` as a single word, although ironically we don't for `tree map`. *shrug* – corsiKa Feb 24 '14 at 21:57
  • 1
    Well, motorcycle is a bit of an edge case (it was, in fact, originally a motor cycle, though now that's something different); `honeyBee` (and not `honeybee`, in fact not "honeybee" but "honey bee"), and `butterfly`. – orome Feb 25 '14 at 04:08
  • 3
    The non-adressed `setUp` case is an edge case though, it's a single word, but `JUnit` historically has it's fixture initialization named `setUp`. – TC1 Feb 25 '14 at 08:21
  • 24
    @TC1 Actually, ["setup" is a noun](http://dictionary.reference.com/browse/setup?s=t), never a verb. "Set up" the correct form of the action. `JUnit` has it right, the rest of us are the edge case. :) – Jason C Feb 25 '14 at 12:49
  • 3
    @JasonC Thanks, **finally** it makes sense why the counter-part is `tearDown` :D – TC1 Feb 25 '14 at 12:52
  • 1
    @corsiKa: actually that does kind of make sense, because in a hash map the hashing is crucial to characterise the behaviour (there is no ordering), while using a tree vs. e.g. an ordered array is an implementation detail that only affects the _performance_ of certain actions. So you emphasise `ʜᴀꜱʜmap` vs. `treeMᴀᴘ`. (Though again one might argue that ordering shouldn't be a "default" characteristic of maps, but then the correct nomenclature would be `hashMap` vs. `treeOrdmap` and `arrayOrdmap`.) – leftaroundabout Feb 25 '14 at 20:00
  • What do you think about words composed by initials like HTTPRequest. Should by written HTTPRequest or HttpRequest? Should by written getISOFormat or getIsoFormat? – Nico Feb 12 '19 at 18:17
  • What if I want to write a function for "Load PDF File"? It would/should be `loadPDFFile` or `loadPdfFile`? But to me, both seem weird... in the first one, to many capital letters are together while in the second one, we changed `PDF` to `Pdf`!! On the other hand, in one of the opensource projects, they have used `Load_PDFFile` (the same way for "Capture XY" they have used `Capture_XY`) while all the other function names, as well as variable names, are in **camelCase**! So, is this the standard practice in camelCase when it comes to such scenario(s)? – Milan Sep 25 '20 at 22:32
44

Part 1
I think what's tripping you up is that some of your examples are compound words, whereas others are not.

  • phone number // not a compound word
  • motorcycle // compound word
  • wavelength //compound word
  • sunblock // compound word
  • Sunday // compound word*
  • motorcycle color // compound word used with a non-compound word.

Compound words do not follow camel case notation for the second word in the compound word.

So it's motorcycle and not motorCycle.

But "phone number" is not a compound word and it would follow camel case notation. i.e. phoneNumber.

And that leads to: motorcycleColor.

If I can't recall if a word is truly a compound word or not, I look it up in the dictionary to be certain.

Part 2
Two of your examples are a little trickier.

  • hash map
  • hash table

They're tricky because some will spell them as "hashmap" and "hashtable". According to the dictionary I just checked, they are separate words and not a compound word. So the correct camel case would be hashMap and hashTable. Not every team follows that convention, so you need to ask your teammates what they prefer and then stick with that. Consistency is more important in this case than what a dictionary may say is correct.

* Some will argue about Sunday being a compound word since other days of the week are not, but for the purposes of this question I'll sidestep that issue. It's easiest to treat as a compound word and therefore no camel case.

  • 6
    The other days of the week were all compounds too: "Monday" <- moon day, Tuesday <- Tiw's day, Wednesday <- Woden's day, Thursday <- Thor's day, Friday <- Frigg's day, Saturday <- Saturn day – kevin cline Feb 24 '14 at 18:04
  • 6
    @kevincline: Those forms of the names of the days are probably considered archaic now, so don't really count for practical purposes. ...Unless you actually write code that looks like `if (currentDay == thorsDay) {...` Hmm... too bad date libraries don't have that as a formatting option when you want to get the full name of the day of the week. – FrustratedWithFormsDesigner Feb 24 '14 at 18:14
  • 15
    @FrustratedWithFormsDesigner: the point was that in modern usage, Sunday is a compound word to the same degree that Monday is: not at all. It's just an accident that the "Sun" in "Sunday" can stand alone, while "Moon day" was shortened to "Monday" – kevin cline Feb 24 '14 at 18:32
  • 6
    Better yet, use better names for your variables than hashMap or hashTable. It's a slippery road that leads to this wonderful line of code: `HashMap hashMap = new HashMap();` – Eric Andres Feb 24 '14 at 22:09
  • Technically, the phrases with spaces can still be compound words; they would just be open compounds. The linked Wikipedia article discusses these types of compound words as well. Jon Hanna's answer gives a more accurate explanation of this from a linguistic perspective. – Bob Aug 25 '23 at 16:43
8

As others have pointed out, camel case is used when joining words. Do not use camel case within a single English word. The problem comes in determining which compounds are single words. Left to themselves, programmers will come to different decisions depending on their knowledge of English. This leads to inconsistencies in capitalization, which are almost as annoying as misspellings.

To prevent this, programmers should use a standard reference (e.g. dictionary.com) when they are unsure about spelling or capitalization. Even so, if consistency in naming is important to your project, there is no substitute for code review.

Picking a single reference for your project will resolve most arguments about capitalization and spelling. There are some compounds like Hashtable that are not in dictionaries, but are capitalized as single words in the Java and C# APIs. You will want to make a project-wide decision about those. In Java, it's "HashMap" but "Hashtable". IMO "Hashtable" is clearly incorrect; it never appears as a single word except as a name in an API.

kevin cline
  • 33,608
  • 3
  • 71
  • 142
4

The simplest way to do camel case is on word delineation.

Examples from your question:

  • phone number: phoneNumber
  • motorcycle: motorcycle
  • sunday: sunday
  • wavelength: wavelength

If you wouldn't split it into two words, you also shouldn't use camel case on it. Otherwise you're using it on syllables and how silly does this look

  • auxIlIArY (This is a 5 syllable word; not to mention the I's looking like crap on non-monospaced/sans-serif fonts).
Jeff Langemeier
  • 1,397
  • 9
  • 19
  • But `phoneNumber` looks as wrong as `passWord` and `setUp`. Shouldn't it be `phonenumber` since its a word of its own and not a concatenation like `motorcycleColor" or `phoneColor` ? – Niklas Rosencrantz Feb 24 '14 at 17:36
  • 5
    phone number is not its own word, put it into google as a single word, it'll happily look up everything that has "Phone Number" not phonenumber. And setup isn't two words, neither is password. – Jeff Langemeier Feb 24 '14 at 17:38
  • 6
    @JeffLangemeier A very small quibble: “setup” is a noun, while “set up” is a verb. Hence if you have an object representing how something is set up it would be called `setup`, while if you had a function to set something up it would be called `setUp`. – bdesham Feb 24 '14 at 21:51
  • 2
    @bdesham I realize that, but I would just stay away from setUp, since a better, less ambiguous verb would be initialize, I actually completely forgot about the verb version of setup. – Jeff Langemeier Feb 24 '14 at 22:14
  • 1
    I would think the one that starts with "wa" could either be `wavelength` or `waveLength` depending upon whether the value in question is relates to propagation velocity divided by frequency, or whether it relates to the "length" (not necessarily distance) of some kind of wave. For example, an audio synthesis library's variable for the number of samples associated with a wave would not be `wavelength` but `waveLength`. – supercat Feb 24 '14 at 23:09
  • 1
    @supercat: good point. But waveLength would be a horrible choice for a sample count because of that ambiguity. Besides, you can't sample a wave, you can only sample a signal. – kevin cline Feb 24 '14 at 23:42
  • 2
    @kevincline: In audio synthesis engines, it's common to have wave tables which contain one or more whole samples of a wave. When playback reaches the end of the table, it loops back either to the beginning (for simple engines) or to some other spot in the wave. To be sure, `WaveLength` by itself would be a bit vague in any but the most simplistic scenarios [does it refer to the buffer size or the length of the looping section] but the words could perfectly well appear in a longer name. – supercat Feb 25 '14 at 00:07
  • 1
    @kevincline precisely, it would make much more sense to use sampleCount or waveSamples or something. – Miles Rout Feb 26 '14 at 09:04
4

This is where a complication with plain English gets in the way of how one later abuses English to fit with the white-space rules of tokens in programming contexts.

Of the example words you give, almost all are compounds. Sunday isn't, as while it originated as a compound, it did so so long ago that it can scarcely be considered one now, especially as its being dedicated to the sun is more a historical curiosity than a strong part of the religious and cultural outlook of English-speaking people.

And in English, the three main ways to write a compound are open (with a space between the two words), hyphenated, and closed (with no space or hyphen between the two). And while there are some rules about hyphenating open compounds in certain situations, there isn't really much in the way of firm rules for knowing what form is used for a given compound beyond seeing what other people do, and there are still times when you'll find two or even all three forms (eggbeater, egg-beater and egg beater for example).

Here, phone number is almost always written open, so it should be treated as two words.

And when inter-capping to form a token, the space or hyphen is removed and the second and subsequent word written in title-case, hence phoneNumber or PhoneNumber as appropriate for your convention.

The thing that makes phoneNumber seem strange is probably that it's more commonly just given as phone in most contexts, or as number when the context is about a telephonic connection.

Jon Hanna
  • 2,115
  • 12
  • 15
2

Insure consistency within the code file.

Promote consistency within the code project.

Prefer consistency within the code library.

The compounding of words to represent concepts changes as we become more familiar with a given agglutination.

For example...

  • 'telephone set' became shortened to just 'telephone'
  • 'telephone' became shortened to just 'phone'
  • 'phone number' was sometimes contracted into 'phone-number'
  • 'phone-number' soon became 'phonenumber'
  • 'phonenumber' is often further shortened to just 'phone'
  • 'cellphone', or just 'cell' are in common usage today
  • 'homephone', and 'workphone' may soon become common as well

Note that the StackExchange spell-checker can't make up its its mind. 'Phonenumber' at the end of the sentence above was fine but it flags the one at the beginning of the sentence (capitalized or not).

As much as most everyone desires there to be "one right way" to do things, when it comes to language, that can never be. By the time you finish your project, usage will probably have changed. Certainly your understanding will have changed and the functionality of the method/et.al. will probably have changed too. (In which case, you should probably change the name appropriately.)

DocSalvager
  • 305
  • 2
  • 8
-1

From a strictly technical (US) perspective, where xxx-yyy-zzzz is what you'd normally think of as a "phone number' the xxx part is properly referred to as the area code, the yyy part is properly referred to as the exchange, and the zzzz is properly referred to as the number.

Since not only is "phonenumber" not a compound word (yet), but if it becomes one, it will incorrectly reference something outside of its creator's intent, I would say that camelCase syntax would require phoneNumber for any variable that references it, but if you're going to do anything with the actual telephone system, I'd use phoneExchangeNumber for the seven-digit and phoneACExchangeNumber for the ten-digit versions.

MLT
  • 1
  • 1
  • 1
    this doesn't seem to offer anything substantial over points made and explained in [this prior answer](https://softwareengineering.stackexchange.com/a/230165/31260) that was posted over 3 years before – gnat May 26 '17 at 16:31