64

Occasionally, the most logical name for something (e.g. a variable) is a reserved keyword in the language or environment of choice. When there is no equally appropriate synonym, how does one name it?

I imagine there are best practice heuristics for this problem. These could be provided by the creators or governors of programming languages and environments. For example, if python.org (or Guido van Rossum) says how to deal with it in Python, that would be a good guideline in my book. An MSDN link on how to deal with it in C# would be good too.
Alternatively, guidelines provided by major influencers in software engineering should also be valuable. Perhaps Google/Alphabet has a nice style guide that teaches us how to deal with it?

Here's just an example: in the C# language, "default" is a reserved keyword. When I use an enum, I might like to name the default value "default" (analogous to "switch" statements), but can't.
(C# is case-sensitive, and enum constants should be capitalized, so "Default" is the obvious choice here, but let's assume our current style guide dictates all enum constants are to be lower-case.)
We could consider the word "defaultus", but this does not adhere to the Principle of Least Astonishment. We should also consider "standard" and "initial", but unfortunately "default" is the word that exactly conveys its purpose in this situation.

closed as primarily opinion-based by gnat, Bart van Ingen Schenau, amon, Andres F., Brian Jan 3 '17 at 22:11

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 15
    I'd use something like "default_value". The meaning stays the same, but you have to type a few more characters. – Mael Jan 2 '17 at 13:23
  • 26
    @Darkhogg if I found either of those in my code I would change them immediately. Spelling mistakes or naming convention violations are not acceptable. – MetaFight Jan 2 '17 at 14:59
  • 26
    @MetaFight - except that in Java, calling a variable that holds a class clazz is practically a de-facto standard. It essentially is part of the platform naming convention. Doing anything else would be a violation of expectations that others might have reading your code, so should only be done if absolutely necessary. – Periata Breatta Jan 2 '17 at 15:08
  • 6
    default as enum value seems contra-productive. It should be a domain-specific name that describes the default. There should be a method to return the default, though. – Thomas Kilian Jan 2 '17 at 15:14
  • 18
    @AndresF. I disagree. I often find it very easy to argue against the designers of Java. I don't hold it against them, though. They were working in the wild west. – MetaFight Jan 2 '17 at 19:59
64

For an enum option you should use title case like Default. Since C# is case-sensitive it will not collide with the reserved keyword. See .net Naming Guidelines.

Since all public members should be title case in .net, and all reserved names are lower case, you shouldn't really encounter this except with local variables (including parameters). And locals would typically have nouns or phrases as names, so it is pretty rare the most natural name would collide with a keyword. Eg. defaultValue would typically be a more natural name than default. So in practice this is not a big issue.

In C# you can use the "@" prefix to escape reserved keywords so they can be used as identifers (like @default). But this should only be used if you really have no other option, i.e. if you are interfacing with a third-party library which uses a reserved keywords as an identifier.


Of course other languages have different syntax and keywords and therefore different solutions this problem.

SQL have quite a lot of keywords, but it is very common to simply escape identifiers, like [Table]. Some even do so for all identifiers, regardless of whether they clash with a keyword or not. (After all, a clashing keyword could be introduced in the future!)

Powershell (and a bunch of other scripting languages) prefixes all variables with a sigil like $ which means they will never collide with keywords.

Lisp does not have keywords at all, at least not in the conventional sense.

Python have an officially recognized convention in PEP-8:

Always use cls for the first argument to class methods.

If a function argument's name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption. Thus class_ is better than clss. (Perhaps better is to avoid such clashes by using a synonym.)

Some languages like Brainfuck or Whitespace avoids defining words at all, elegantly sidestepping the problem.

In short there is no language-independent answer to your question, since it highly depending on the syntax and conventions of the specific language.

  • 2
    You shouldn't rely on case sensitivity alone, though. While it's not likely to be a problem in practice, not all .NET languages are case-sensitive, so you might run into unexpected problems at some point. – Vivelin Jan 3 '17 at 11:02
  • 6
    @Vivelin: You shouldn't have public members or type names which differ only in case, since this might lead to the problems for other language. But this is unrelated to what I suggest, since keywords are not identifiers (and other languages will have other keywords). – JacquesB Jan 3 '17 at 12:38
  • Even if the @ syntax is available, it is IMHO best reserved for scenarios where one needs to interact with libraries written languages with different keywords. Even there, I think it might have been better to have a language feature somewhat like #define, but right-hand operand would always be interpreted as a case-sensitive identifier. That would allow many kinds of naming conflicts to be resolved (including, for case-insensitive languages, the importation of symbols that are identical except for case). – supercat Jan 3 '17 at 15:33
  • @Vivelin not all .NET languages are case-sensitive -- I know of VB.NET and Powershell; are there any others? – Zev Spitz Jan 3 '17 at 19:57
  • @ZevSpitz the OP specifically called out C#, which is why I think Vivelin used it as his example, however as you say VB.NET is not case-sensitive, so as usual, I would think it would come down to a per language basis. Not all languages have the same reserved words – Shaggy13spe Jan 3 '17 at 20:46
22

I would append an underscore (default_)

Pros:

  • simple
  • obvious(why else would you append an underscore?)
  • consistent
  • easy to use
  • works in all modern languages I know
  • closest to the logical option

Why I dont like other solutions:

Synonym:

  • hard to find
  • often not the exact same meaning(nuances)

Appending/Prepending a word:

  • inconsistent(defaultValue, defaultItem)
  • increased verbosity without increased readability

Changing letters(clazz instead of class):

  • inconsistent(clazz, klass, klazz)

Appending a number(default1):

  • raises the question for default2

Appending/Prepending a letter:

  • non obvious(programmer has to guess that it was used for namecollision and not a shortcut for something else)

Escaping a Keyword(@default(c#), `default`(scala))

  • only possible in some languages
  • rarely used feature, mainly for compatibility to other languages
  • makes it harder to use for users of your api(they have to know how to do it and remember how to do it)

When would I not use it:

  • existing, widely used other convention
  • I already know a fitting synonym
  • in your specific enum case I would follow @JacquesB answer
  • 7
    This is a solution often used in Python. I am not advocating it as the most elegant, but it works. – fralau Jan 2 '17 at 19:53
  • 1
    @fralau Python ist especially bad - I really hate identifiers like "input" – Christian Sauer Jan 3 '17 at 6:31
  • In a lot of languages one sees klass for a variable where class is a reserved word. I've never seen defawlt but it's the same idea. I'd prefer default_ (and probably class_ if not trampling over any established conventions by so doing). – nigel222 Jan 3 '17 at 10:05
  • You didn't include the option of escaping the keyword. – CodesInChaos Jan 3 '17 at 11:13
  • 1
    You make valid, sensible arguments, although I'm not sure it's "obvious why the underscore was used". I've rarely worked with froods that know all the keywords of the languages they're working in! – Protector one Jan 3 '17 at 15:05
18

"Default" is probably not a helpful enum value. It represents a behavior that may change depending on the context where it is used.

That being said, if your language is case sensitive, then use a different case for the word. (Default vs default)

Or better yet, make the extra effort to type a few more letters and call it DefaultValue.

  • 3
    I agree. "Default" offers no indication what the value is. Consider enum ErrorHandlingLevel { Default = 0, ... } vs enum ErrorHandlingLevel { None = 0, ... }. In the second example, the fact that None is the default can be made known by setting the enum value to 0, using xmldoc, or explicitly in code. You get the added benefit of knowing what it means when an object has its ErrorHandlingLevel set to None. Compare that to inspecting an object with ErrorHandlingLevel set to default. – Harrison Paine Jan 3 '17 at 17:53
9

I would highly recommend NOT changing naming convention locally (or adding meaningless characters) for the purpose of disambiguation (like have been suggested in other posts). It creates confusion if intent is not obvious and may raise questions as to why was it named this way. It can be solved without it.

In every case it should be possible to either use a word with synonymous meaning or make the name more specific (or even verbose). Even when it may introduce repetition of context it may be a better solution.

For example, lets say you have an enum Mode that should expose a default value like in your case. Naming it default_mode may not seem the best due to the repetition, but it avoids ambiguity while conveying desired meaning.

  • You make a valid point, but I'm still unsure what creates more confusion: having a consistently appended fragment or using different words for every situation. Case against the former option being of course, that the situations where it would be used in the first place are (hopefully) so rare that consistency can not be inferred from existing code. – Protector one Jan 4 '17 at 9:01
3

You'll need to use different or modified word(s), that is clear.
So this usually means either

  • a completely different word
  • a prefix
  • a suffix

Another factor to determine is how to join the multiple words and the options are usually

  • allonewordnoseparators
  • words_with_underscores-or-dashes (snake_case)
  • CapitalizationForClarityAndReadability (CamelCase)

My suggestion is to use a prefix or suffix and underscores/dashes, e.g.

local_default, my_default, a_default, domain_specific_default
default_local, default_me, default_a, default_domain_specific

local_default has the advantage that all the locals are aligned and thus stand out quickly but the disadvantage that you always have to read on to the second portion to get the unique name. default_local has the converse advantage that the unique variable name is quickly seen, but locals are not always so easily grouped visually.

A couple of examples for the the domain_specific approach I have seen are: vehicle_model instead of model which was a reserved word; room_table for a SQL table as table is a reserved word.

The other two options I have seen languages or scripts use are:

  • quotes or backtips to surround variables names and thus allow the use of reserved words. Similar to this I could imagine some languages might allow a special character such as a backspace to escape a name.
  • spaces in variables names.
  • As a little maybe interesting side note: I've seen words_with_underscores-or-dashes referred to with two names - snake_case when using the underscore and kebab-case when using the dash. I found the latter funny. – VLAZ Jan 3 '17 at 16:23
2

Obviously, do what you can to avoid that situation. I've been writing software since the late 1970s and the times I've really, really had to fudge a reserved word is well under ten, probably closer to five.

There are lots of things you can do, such as doubling the first or last letter (reservedd) or adding a leading or trailing underscore (reserved_). What's appropriate will depend a lot on the conventions used language you're writing, especially with regard to leading or trailing underscores. Also try not to do things with case that could be misread by humans (e.g., using Reserved when it differs from reserved).

Once you've picked something, put it in your coding guidelines, make sure people know about it and that it's used consistently. I even go so far as to add a reminder comment so readers don't think it's a typo and know they'll be seeing it again:

int ccase;  // Name dodges a reserved word
  • 10
    Not the downvoter, but the "doubling the first or last letter" suggestion sent chills down my spine.... – Willem van Rumpt Jan 2 '17 at 18:22
  • @WillemvanRumpt I don't like doing it, either, but once in a great while it comes down to a choice between doing gymnastics to avoid a reserved word that prompts a lot of head scratching or a weird-looking identifier that prompts only a little. – Blrfl Jan 2 '17 at 18:53
  • 6
    No judgement intended, just....chills....cold ones... ;) – Willem van Rumpt Jan 2 '17 at 19:00
  • 1
    Postpending an underscore is better than a doubled last letter. (Any votes for classs? ) – nigel222 Jan 3 '17 at 10:08
  • 1
    Coding guidelines! That would be nice to have! Good point. – Protector one Jan 3 '17 at 15:03
2

In C#, you can prepend the name of an identifier with @. This tells the compiler to treat the name as the name of an identifier and not as a possible keyword.

enum @default {Sat, Sun, Mon, Tue, Wed, Thu, Fri}; 
  • 3
    wonder who would vote up this "answer" that merely repeats point already made (and much better presented) in a top voted answer a day before – gnat Jan 3 '17 at 15:21

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