Most programming languages do not permit spaces in variable names. However, it is often useful to have a variable name that is composed of several words, such as “destination file” or “error handler”. Programmers have tended to work around this issue by using either underscores (“destination_file”, “error_handler”) or camel case (“destinationFile”, “errorHandler”). But what if you were in a position to allow spaces in variable names — is there a good reason not to allow spaces?
The reasons that spaces were historically disallowed in variable names is that it tends to introduce ambiguity into language grammars, where a space separating two identifiers may be meaningful (e.g. Haskell). However, I believe that some languages could almost allow spaces in variable names, because two identifiers (i.e. not keywords) separated by a space are a syntax error. In Java, for example, the only situation I can think of that it is valid to have two identifiers separated by only a space is during declaration of variables, methods and parameters, where the type and name are separated by whitespace (“int x”, “String getText()”).
If we use a symbol, let’s say double colon, to separate types and names, I think we could allow spaces in Java variable names without ambiguity, e.g. (newline added solely for readability)
int :: x position of rocket = x position of spaceship + x rocket launch offset;
It may look a bit alien to an experienced coder, but there’s no ambiguity in parsing that, and I don’t see that it is necessarily worse than:
int xPositionOfRocket = xPositionOfSpaceship + xRocketLaunchOffset;
(Ok, the plus symbol is a bit buried in the first line, but a little syntax colouring would probably offset that.)
In a text-based language like Java, you do have the complication that if one of the words in your variable name is a keyword — or begins with a digit — it may become hard to parse. In contrast, in a block-based language like Scratch, there is no such problem — variable names are typed into their own text field, so there is no parsing problem and thus Scratch allows spaces in variable names.
When you use a variable in Scratch, you select the declared name from a dropdown. Thus there is no requirement for the user to type the exact declared variable name, as there is in most other systems. To this end, I would suggest prevent leading and trailing spaces on a variable name (parsing that would definitely be a nightmare), and also for sanity, preventing multiple adjacent spaces in a variable name. There is no good reason to have a difference between “x position” (one space) and “x position” (two spaces), and allowing a difference will only lead to madness while you track down a syntax error caused by an accidental double space.
If you were designing a language and could allow spaces in variable names, would you do it? Is there any reason not to allow them, if you can overcome the potential parsing difficulties?