Search code examples
naming-conventionsnamingconventions

Variable with same name as keyword


Is there a good way to create a variable, function, class, etc. with the same name as a keyword?

What I usually see (and follow myself) is using slightly different names. For example, using clazz or Class instead of class.

But using a different name than what is desired feels very hacky and can sometimes be confusing.

In C#, you can use the @ operator:

int @class = 0;

However, I'm unaware of equivalents in other popular languages. Are there any?

If not, are there workarounds? Or are there at least naming conventions to use?


Solution

  • With the word class as example I think the best option is to either find a synonym, like kind or category, or add a contextual word to the identifier, e.g. priceClass or classKind. Some words can also be abbreviated, so if function is a keyword you could use the identifier func.

    Some programming languages avoid this problem altogether by using upper case keywords or have keywords with special syntax. The advantage with this approach is also that new keywords can be added to the language without invalidating existing code.