67

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.

Protector one
  • 799
  • 1
  • 6
  • 13
  • 15
    I'd use something like "default_value". The meaning stays the same, but you have to type a few more characters. – Mael Jan 02 '17 at 13:23
  • 3
    `dflt` is a relatively common substitute for `default` that I'd say everybody would understand. For other reserved words there might be different common substitutions (such as `clazz` for `class`, at least in Java) – Darkhogg Jan 02 '17 at 14:29
  • 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 02 '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 02 '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. –  Jan 02 '17 at 15:14
  • 3
    @PeriataBreatta hrm. Java comes from a history of cowboys, I guess. – MetaFight Jan 02 '17 at 15:22
  • 3
    related: [Intentional misspellings to avoid reserved words](http://softwareengineering.stackexchange.com/questions/62060/intentional-misspellings-to-avoid-reserved-words) – Andres F. Jan 02 '17 at 15:24
  • 1
    In python PEPA8 mandates a trailing underscore. For example: `class_`. It's probably aestethically ugly, but I prefer it to mispellings which, if not well known, can be obscure. – Bakuriu Jan 02 '17 at 17:32
  • 1
    @MetaFight Naming conventions such as spelling it `clazz` *are* part of Java's standard library. Hard to argue against the designers of the language :) – Andres F. Jan 02 '17 at 18:56
  • 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 02 '17 at 19:59
  • @MetaFight So what would you use as a replacement for `clazz` then in the context we're talking about? – Voo Jan 02 '17 at 20:20
  • 1
    @Voo Show me where clazz is used and I'll do my best. – MetaFight Jan 02 '17 at 20:35
  • 4
    I typically use `_class` in Java, somewhat like the Python convention. `clazz` is just offensively hideous. – Torisuda Jan 02 '17 at 20:37
  • 3
    @MetaFight That's an odd fight to pick. Naming conventions are arbitrary; adding extraneous symbols is as arbitrary as writing with standard misspellings. And neither has nothing to do with cowboy coding, which means something else (related to not playing well in team contexts). – Andres F. Jan 02 '17 at 20:46
  • 4
    @MetaFight Stuff having to do with reflection, for example take `public Class extends U> asSubclass(Class clazz)` from [`java.lang.Class`](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/lang/Class.java#3400). How would you refer to the parameter? If you suggest a shorter `c` I, being a fan of Haskell, would agree. But Java devs are used to longer names even for generic parameters, so that won't do and it would be a serious violation of naming conventions. What matters is that if you break a widely accepted convention, you're doing it wrong :) – Andres F. Jan 02 '17 at 20:58
  • 4
    @MetaFight Particularly things dealing with class loaders (native and Java) comes to mind, Andres' example works just as well though. I have a hard time seeing what objectively better solution you'd pick. Establishing a naming rule that is universally followed for the particular niche strikes me as a perfectly valid solution. Using nondescript one char names (`c`) or appending some filler char (eg `class_` which is what python standardized on) are alternatives but none is objectively better than the other. – Voo Jan 02 '17 at 21:32
  • 3
    @AndresF. if I'd seen a var named `c` in Java, I'd almost immediately assume it's a `char` variable. Single-character names were conventionally used for simple, foo-bar-ish primitive values mostly (`int i, byte b, char c, boolean b, float f, long l, double d, short s` etc.), with `String s` appearing from time to time since it's a commonly used builtin type too (I prefer `String str` to avoid confusion with `short`; in most contexts the difference between them is obvious enough, though). –  Jan 02 '17 at 22:30
  • 1
    @AndresF. Since it's a subclass, why not call it `subclass`? – CJ Dennis Jan 03 '17 at 00:06
  • @CJDennis It's not a subclass. It's a class. It says so in the type! In general, so as not to miss the forest for the tree, you often have this problem whenever you are dealing with reflection and generic class objects (where your domain doesn't dictate what to call the variable except... well, "class"). Instead of `clazz` you could use a shorter name like `c`, like some other languages favor; however with Java you're stuck with existing conventions. When using a language, it's always best to stick to what's already in use, instead of using conventions of, say, Python in Java. – Andres F. Jan 03 '17 at 01:49
  • 2
    @AndresF. OK, so `asSubClass` means it's a class, because a class can't also be a subclass. I'll keep that in mind when I'm programming in Java: Java programmers like to name things misleadingly. I guess all strings should be named `ztring` or `s`, all arrays `arrai` or `a`, etc. to avoid confusion. – CJ Dennis Jan 03 '17 at 01:59
  • @CJDennis No need to be snarky. I suggest when programming in a language you follow it's accepted conventions, unless you have a *very good* reason not to. Neither `ztring` nor `arrai` are needed in Java because neither `string` nor `array` is a reserved word. I've already explained why `s` and `a`, while not terrible choices, are not the most common in Java (but you'd be fine using this convention in other languages). I understand you might not *like* the convention, but it's not there for you to like it -- it's there for you to have a common language with other programmers. – Andres F. Jan 03 '17 at 02:04
  • @CJDennis BTW, I'm not an authority in the Java language, nor do I particularly like it. I'm just mentioning its conventions. If you want to say you dislike Java, good for you! I too dislike it :) But when programming in Java I try (within reason) to follow its conventions unless the rest of the team agrees not to for a good reason. – Andres F. Jan 03 '17 at 02:07
  • @AndresF. Could you explain why a class can't be a subclass, and therefore why `subclass` is a bad name despite `asSubClass` appearing right before the actual class being named? I've obviously missed your point. – CJ Dennis Jan 03 '17 at 02:10
  • @CJDennis It doesn't matter; that was just an example. You might as well ask the designers of Java. – Andres F. Jan 03 '17 at 02:17
  • 3
    @CJDennis The method takes as a parameter an arbitrary class and returns a subclass. Naming the input `subclass` makes no sense. – JollyJoker Jan 03 '17 at 12:49
  • 1
    But naming it superclass or parent does make sense. I would say class or clazz or c are all poor names for it. – Caleth Jan 03 '17 at 13:28
  • @AndresF. Naming conventions are entirely arbitrary unless there is an officially suggested convention (like in C#, and probably Java). You assume your only options are adding extraneous symbols or misspellings. That's not true. Using a *different* more *meaningful* name is another, better, option. Also, choosing a spelling mistake over a more meaningful name *is* cowboy coding. Back when these APIs were written I'm assuming that was much more of the norm than it is today. That's why I don't hold it against the Java designers. – MetaFight Jan 03 '17 at 13:50
  • @AndresF. To stretch out the metaphor even more, you could say they were trailblazing and put more focusing on gaining new ground than on readability. And for your example, I would probably call the parameter something like `superClass`. Yes, it's still clumsy, but it uses information about the parameter and its properties to name it. No extraneous characters. No spelling mistakes. – MetaFight Jan 03 '17 at 13:50
  • @MetaFight There is often no more meaningful name when doing reflection and metaprogramming. In normal usage this problem doesn't arise (who needs to mention classes then? Maybe school classes, in which case you can always call them schoolClasses). In other languages, the standard is that the more abstract and generic the parameter, the shorter the name; in such languages an identifier such as `c` is the standard convention. I'd like to use it in Java as well, but *it's not the convention there* so I usually don't. This is unrelated to cowboy coding and you're using the term incorrectly. – Andres F. Jan 03 '17 at 14:20
  • @MetaFight You and CJDennis are too focused on this specific example, which perhaps wasn't the best one. The point was that when all you know about the parameter is that it's a class, because you're doing metaprogramming and reflection and your "domain" is the Java language itself, `clazz` is an acceptable name. If it wasn't the convention, then it wouldn't be acceptable. But it is. Following an alternative convention (say, Python's or Haskell's) would be a "less than good" idea ;) – Andres F. Jan 03 '17 at 14:22
  • A more general comment: because this question is unrestricted to a specific language, and because different languages (and even project maintainers!) use widely different conventions, and because there is no "best" alternative, I'd say this question is probably both too broad and primarily opinion based... – Andres F. Jan 03 '17 at 14:34
  • Per your example, the suggested naming convention for C# enums is to use PascalCase (camelCase with first character capitalized). This would allow you to use the value `Default` with no issues at all. – Harrison Paine Jan 03 '17 at 16:15
  • 3
    I don't understand the issue here. A default (for example) is always a default *of some value*. I have many consts (const conventionally all caps, different discussion please) like "DEFAULT_MINIMUM_MOVEMENT". The word "Default" by itself means nothing. The same logic can generally be applied to other key words. – MickeyfAgain_BeforeExitOfSO Jan 03 '17 at 16:32
  • 1
    @mickeyf Nailed it. Default *what*? DefaultMode? DefaultValue? DefaultCase? Better yet, what *is* the default? What does `CaseSensitivity.Default` do, for example? – anaximander Jan 03 '17 at 19:07
  • You should never name any enum value starting with a small letter in the first place, so your specific example is not very motivating. And the answer to the more general question will vary by language. – Eric Lippert Jan 03 '17 at 20:19
  • @Anaximander: What if my enum is already called "Mode"? Would you still name it "Mode.DefaultMode"? – Protector one Jan 04 '17 at 08:40
  • @Eric: I agree that was a poor example in hindsight. This question is more about general guidelines, which shouldn't differ too much from language to language! – Protector one Jan 04 '17 at 08:42
  • @Mickey: The name of the enum provides valuable context you shouldn't dismiss. – Protector one Jan 04 '17 at 08:47
  • 1
    @Protectorone To be honest, I'd name it whatever the default mode *does*. If I have a "fast mode" and a "safe mode", they're self-explanatory. I don't know what "default mode" does by looking at its name. – anaximander Jan 04 '17 at 08:59
  • @Anaximander: It sometimes is more important to know that a mode is the default, than what it entails. – Protector one Jan 04 '17 at 09:03
  • @Protectorone It does, and I don't. I'm not limiting this to enums, which were used only as an example. – MickeyfAgain_BeforeExitOfSO Jan 04 '17 at 12:40
  • 1
    @Mickey: I'm not limiting this to the term "default", which was only used as an example. – Protector one Jan 04 '17 at 12:58

7 Answers7

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.

JacquesB
  • 57,310
  • 21
  • 127
  • 176
  • 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 03 '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 03 '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 03 '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 03 '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 03 '17 at 20:46
  • @Shaggy13spe My question is entirely a side point - what other .NET languages besides VB.NET and Powershell are case-insensitive? – Zev Spitz Jan 03 '17 at 22:52
  • @ZevSpitz, not many that's for sure. There are other languages that have been targeted to .NET, COBOL for instance which is case-insensitive. One thing to note, even though VB.NET itself is case-insensitive, it runs on a case-sensitive runtime, which means code that depends on runtime introspection would need to take that in to account. – Shaggy13spe Jan 04 '17 at 15:03
24

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
Siphor
  • 773
  • 4
  • 6
  • 7
    This is a solution often used in Python. I am not advocating it as the most elegant, but it works. – fralau Jan 02 '17 at 19:53
  • 1
    @fralau Python ist especially bad - I really hate identifiers like "input" – Christian Sauer Jan 03 '17 at 06: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 03 '17 at 10:05
  • You didn't include the option of escaping the keyword. – CodesInChaos Jan 03 '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 03 '17 at 15:05
  • @nigel222 `clazz` is common, as well. – SnakeDoc Jan 03 '17 at 17:54
  • @ChristianSauer `input` isn't a reserved word in Python, just a builtin function. Re-using the name is syntactically valid, if bad practice - although in Python 2, using `input` for input is also bad practice. – James_pic Jan 03 '17 at 17:55
  • @CodesInChaos: Rarely an option. What languages even allow that? I think Scala does, but I don't know of any others. – user2357112 Jan 03 '17 at 17:57
  • @user2357112 C# and most other .net languages do, since .net is designed as multi-language environment. – CodesInChaos Jan 03 '17 at 18:00
  • Appending/Prepending a word is only inconsistent if you use it inconsistently. But even then, it's still (IMO) better than an underscore. For the past year, I've been working a project where we are contractually obligated to maintain an average identifier length of 10 characters, and an average method name length of 15 characters. While initially it was hard to come up with longer names (and all that extra typing), it has been a benefit to our work, as our code is more readable. There's a balance, to be sure, since we don't want sentences, but compound words make great variable names. – Kent A. Jan 03 '17 at 18:43
19

"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.

Kent A.
  • 880
  • 4
  • 9
  • 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 03 '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.

Sopel
  • 202
  • 1
  • 5
  • 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 04 '17 at 09: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.
Michael Durrant
  • 13,101
  • 5
  • 34
  • 60
  • 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 03 '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
Blrfl
  • 20,235
  • 2
  • 49
  • 75
  • 10
    Not the downvoter, but the "doubling the first or last letter" suggestion sent chills down my spine.... – Willem van Rumpt Jan 02 '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 02 '17 at 18:53
  • 6
    No judgement intended, just....chills....cold ones... ;) – Willem van Rumpt Jan 02 '17 at 19:00
  • 1
    Postpending an underscore is better than a doubled last letter. (Any votes for `classs`? ) – nigel222 Jan 03 '17 at 10:08
  • @nigel222 Absent empirical evidence that X makes the code run better or more readable makes statements of "X is better than Y" are [entirely a matter of opinion](http://softwareengineering.stackexchange.com/questions/204443/coding-convention-regarding-the-usage-of-underscores). This is why the answer recommends finding out what's appropriate on a language-by-language basis. – Blrfl Jan 03 '17 at 13:10
  • 1
    Coding guidelines! That would be nice to have! Good point. – Protector one Jan 03 '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](http://softwareengineering.stackexchange.com/a/339291/31260) a day before – gnat Jan 03 '17 at 15:21