49

I often see code that include intentional misspellings of common words that for better or worse have become reserved words:

  • klass or clazz for class: Class clazz = ThisClass.class
  • kount for count in SQL: count(*) AS kount

Personally I find this decreases readability. In my own practice I haven't found too many cases where a better name couldn't have been used — itemClass or recordTotal.

An example from the JavaDocs for Class show this in the parameters:

 public <U> Class<? extends U> asSubclass(Class<U> clazz)

Does this show a reasonable use case?

Nicole
  • 28,111
  • 12
  • 95
  • 143
  • 9
    For the record: In Python, `cls` is a common (in fact, the one idiomatic) name for variables/arguments contining actual classes (the ones you declare with the `class` keyword and which everything is an instance of). –  Mar 25 '11 at 19:48
  • 14
    You don't like `typedef char ínt`? – Jeff Mar 25 '11 at 20:50
  • @Jeff Is that legal? Shouldn't the first one be a "letter" (a-z, A-Z), or underscore? (I'm talking about C/C++; although, I think they're the only languages with `typedef`.) – Mateen Ulhaq Mar 25 '11 at 22:36
  • 14
    @muntoo You're right. I also get compiler errors for `iñt`. There goes my plan for world domiñation. – Jeff Mar 25 '11 at 23:01
  • 1
    I have broken this rule... and now I feel shame. – jmq Mar 26 '11 at 00:25
  • 3
    Don't do it. I can honestly say that I've never seen this before, and if I did, I'd immediately rename it. Just abbreviate if you *have* to use a non-descriptive variable name (`Class c`). – Cody Gray - on strike Mar 26 '11 at 15:14
  • Possible duplicate of [How to name something when the logical option is a reserved keyword?](https://softwareengineering.stackexchange.com/questions/339285/how-to-name-something-when-the-logical-option-is-a-reserved-keyword) – Deduplicator Jul 31 '19 at 16:05

12 Answers12

65

IMHO, this is a very bad idea. Reserved words are reserved for a reason, and doing this does decrease readability.

I also entirely agree with your second point. Naming a variable class, even if you could do it, would be just as bad as naming it tmp or a. What kind of class? A class of what? Names should be descriptive.

Dima
  • 11,822
  • 3
  • 46
  • 49
  • 15
    "Reserved words are reserved for a reason" <-- This. (Which, ironically enough, is reserved.) – trycatch Mar 25 '11 at 20:18
  • 17
    +1 because you are right. But if you were writing classroom scheduling software, or something, class might be a legitimate variable or class name... – CaffGeek Mar 25 '11 at 20:26
  • 1
    @Chad: even in that domain the word "class" can be ambiguous. For instance, it may mean "course" or it may mean "lecture". :) – Dima Mar 25 '11 at 21:31
  • 9
    Meh. "_Reserved words are reserved for a reason_", which is that language designers are lazy. There are quite a few sophisticated languages where words are only reserved in the specific places where they're used. But Ritchie started this trend when he needed a lightweight compiler for C, and most language designers have learned it from there. – Ross Patterson Jan 07 '13 at 12:19
  • 14
    no Ross, it's because programmers (and readers in general) have an expectation of things to have reasonably unambiguous meaning (which is why learning foreign languages is often so hard, all the things with double meaning, or meaning different from the language you were raised in from childhood where you never notice those ambiguities because they're part of your cultural heritage). – jwenting Jan 07 '13 at 12:31
  • 2
    @Dima We could argue this all day, but I have to get to lecture. – Kieveli Jan 14 '14 at 19:08
  • @Kieveli: funny. – Dima Jan 14 '14 at 20:38
  • 1
    @RossPatterson Language Designers are lazy? Ever designed a language from the ground up? – Allen Clark Copeland Jr Nov 29 '15 at 22:18
  • 3
    @AlexanderMorou Nope, and neither have most language designers, they just start with someone else's design. But look at Algol, Fortran, PL/I, Rexx, and other languages not based on C, and you'll see that grammars without reserved words are certainly possible, just harder. Ritchie had a good reason - the Unix folks felt every keystroke mattered, and on a PDP-11, every CPU cycle mattered. Today? Not so much. – Ross Patterson Nov 29 '15 at 22:35
  • @RossPatterson It's more a matter of the complexity it adds. The maintainability of the code, the number of ambiguities it reduces the code complexity by making it universally reserved.Typically languages version better by making reserved words `case specific` like you're talking, such as the 'var' keyword in C#, but each time you allow a keyword to be a valid identifier without any special escape, you could potentially increase the complexity of the lexer, parser, or introduce an ambiguity that can be a pain even when the parser is hand-written. Point is: calling it `lazy` seems a bit much. – Allen Clark Copeland Jr Nov 30 '15 at 01:40
  • Curious - if you had a method with the signature `public boolean watchClass(Class)` are you suggesting there's something more required than `watchClass(Class clazz)`? I suppose you could do `watchClass(Class classToWatch)` but that seems quite poor and decidedly inferior to the first option. – corsiKa Jul 26 '17 at 14:46
23

Python's Style Guide calls out this problem specifically, and suggests:

If your public attribute name collides with a reserved keyword, append a single trailing underscore to your attribute name. This is preferable to an abbreviation or corrupted spelling.

This seems like a pretty good general rule, assuming it doesn't conflict with the semantics of a particular language.

Ryan
  • 339
  • 1
  • 3
  • 8
    I feel this is really poor advice from a style guide. If your attribute name is so close to a keyword, you should find a better name. Simply sticking an underscore on the end doesn't add any meaning and make's it likely to confuse the next guy that reads the code. – Wayne Johnston Mar 26 '11 at 03:41
  • 18
    @Wayne: How are you going to name the union operation in a union-find structure when `union` is a keyword (as in C)? Are you going to call it `foo` just because it shouldn't look like `union`? – Fred Foo Mar 26 '11 at 10:17
  • OTOH, `cls` is standard argument name for class method. Also for example in Django objects have `.id` attribute, which of course conflicts with `id` built-in function. – vartec Jan 07 '13 at 13:45
  • @larsmans I'm not a native English speaker, so forgive me if I'm wrong, but AFAIK *union* is a noun, not a verb. If it describes an operation, why not call it *unite* and the naming problem is gone? Because, at least for my understanding, you don't union two sets, you unite them into a union. Am I missing something here? – Golo Roden Jan 15 '14 at 13:01
  • 1
    @GoloRoden I've never heard anyone say they were "uniting" two sets when computing the union. It's just not part of the lingo. "Merge" would be better, but a `merge` method would still need documentation explicitly stating that it implements union and was renamed for purely technical reasons. – Fred Foo Jan 15 '14 at 14:13
  • Yes, that's right. The point I wanted to make was basically just that *union* is no verb, but an operation should be described by a verb (IMHO). – Golo Roden Jan 15 '14 at 14:16
  • 2
    @GoloRoden According to Merriam-Webster it's not a verb, but see [this answer](http://english.stackexchange.com/a/196124/5491). – maaartinus May 11 '15 at 01:29
18

Code smell.

string stringVariable = "";

The above code tells me nothing about the variables intended usage.

class Klass

Same problem

string UserNameString = "bmackey"

The above code should not require keyword string appended to variable name. If you find yourself needing to identify types by variable name, your code is too long. Condense-refactor.

P.Brian.Mackey
  • 11,123
  • 8
  • 48
  • 87
  • It doesn't tell you anything because it's not "code", it's an isolated variable declaration. A "class" or "klass" may very well tell you all you need to know. For example, a generic method may receive a `Class` parameter, and this can make sense. So I disagree that it's a code smell. – Andres F. Nov 30 '15 at 13:52
5

Personally, I think it's a perfectly valid option for your code style.

They're reserved words so the compiler doesn't have to decide if you meant the language-mechanic or your variable. With that in mind, it implies that they expect people to have a need for a variable like a reserved word.

Going through the source bundled with JDK 1.6 R21, I find 917 occurrences of "clazz". Apparently, they thought it was acceptable style.

How does your team feel about it? If you think it's bad, but the other 9 guys on your team think it's good, then you have to bite the bullet and accept it. As long as there's communication about what is okay and what isn't, and you're bringing up issues you see as you see them, it should be just fine.

How your team feels about code style is more important than my opinion, or anyone else's in this post. That goes for this and any other code style decisions you might have.

corsiKa
  • 1,084
  • 6
  • 13
  • 1
    Right, but eventually your team will change. Many years down the road there will be some poor guy looking at your code full of klasses and clazzes and saying "WTF!". – MrFox Jan 07 '13 at 17:59
  • 4
    If you are using both `klass` and `clazz` that's a bad thing. You need to be consistent so they only have to learn it once. And ideally this is spelled out in the teams style guidelines too, so it's not much of a surprise. – corsiKa Jan 07 '13 at 18:25
  • Code is written not just for the people on your team, but for the rest of the world to read. When your team are all on a bus that goes over a cliff, somebody else gets to start reading the code. Use names that completely and concisely describe what the variable is, not how it's represented. – Rob K May 11 '15 at 15:00
  • 1
    No, simply no. Your team is far, far more likely to rotate members slowly over time. You can plan for one person getting hit by a bus, but you can't plan for your entire team getting hit by a bus. Most code is written for maybe a dozen people ever needing to read it, half of them during code review. – corsiKa May 17 '15 at 06:30
4

Intentional misspellings to avoid reserved words is a bad idea.

  • Misspellings are hard to distinguish from the correct spelling, therefore they make the code harder to read.

  • Misspellings are hard to remember, so that several inconsistent misspellings are likely to compete within code, which makes code harder to write and harder to read.

  • Reserved words refer to the language being used to solve the problem, not to the problem itself. A variable name should point to a concept related to the problem.

It is therefore better to pick an alternative, descriptive name, or if no satisfying alternative exists, to qualify the reserved word as in:

public static Method findBenchmarkMethod(BenchmarkRecord benchmark) {
    Class<?> benchmarkedClass = ClassUtils.loadClass(benchmark.generatedClass());
    return findBenchmarkMethod(benchmarkedClass, benchmark.generatedMethod());
}
Peter Mortensen
  • 1,050
  • 2
  • 12
  • 14
user40989
  • 2,860
  • 18
  • 35
3

Class clazz smells like "I did not bother to try to come up with a good name". A variable is always representing something, and a good name describes that. I refuse to imagine that clazz for instance under any circumstances is the best name possible. Is it a reference to a class -> class_reference, is is a copy of a class object -> class_copy, etc. Possibly also dropping "class" and just use the descriptive word, e.g.

java.lang.SecurityManager.checkMemberAccess(Class<?> clazz, int which)
Parameters
    clazz -- the class that reflection is to be performed on.

Here clazz is the target class that the check is to be performed on, so

checkMemberAccess(Class<?> target, int which)

would much better describe what the parameter is used for than clazz ever will.

hlovdal
  • 220
  • 3
  • 13
  • IMHO it's not better, you could call it 'classToBeAccessed` or whatever, but any more descriptive name just shows the obvious. I like long names only if they provide useful information. – maaartinus Jan 14 '14 at 11:52
  • 1
    `classToBeAccessed` is a good name indeed (`classToBeChecked` would perhaps be even better). – hlovdal Jan 14 '14 at 15:51
1

If they use a reserved name for a variable, it's a poorly named variable. Even if it is a legitimate name, such as Class for classroom software.

Poorly named variables are a sign of poorly thought out or casual code -- beware of other gotchas in the Piece of Software you are maintaining.

thursdaysgeek
  • 1,303
  • 8
  • 18
0

I often see code that include intentional misspellings of common words that for better or worse have become reserved words:

klass or clazz for class: Class clazz = ThisClass.class

kount for count in SQL: count(*) AS kount

Personally I find this decreases readability. In my own practice I haven't found too many cases where a better name couldn't have been used — itemClass or recordTotal.

However, it's so common that I can't help but wonder if I'm the only one? Anyone have any advice or even better, quoted recommendations from well-respected programmers on this practice?

For local variables and formal arguments, it just doesn't matter.

Any name is fine as long as it is not intentionally misleading or annoyingly distracting. In your example:

public static Method findBenchmarkMethod(BenchmarkRecord benchmark) {
    Class<?> clazz = ClassUtils.loadClass(benchmark.generatedClass());
    return findBenchmarkMethod(clazz, benchmark.generatedMethod());
}

it doesn't matter whether the single local variable is "clazz" or "klass" or "cls" or simply "c". I would probably just inline the expression:

return findBenchmarkMethod(ClassUtils.loadClass(benchmark.generatedClass()),
                           benchmark.generatedMethod());

The length of a variable name should be related to the variable's scope. For local variables in short methods (and they should all be short), very short names are fine.

kevin cline
  • 33,608
  • 3
  • 71
  • 142
  • your inline looks incorrect `ClassUtils.loadClass(benchmark.generatedClass())` => `benchmark.generatedClass()` - lost `ClassUtils.loadClass` along the way – gnat Jan 14 '14 at 17:51
0

One benefit to creative spelling, is better search-ability. I think it's far easier to do a full code search for unique things, than for common words, where too often you will find all of the wrong things, and 1000 of them. As an example, I used to own kzpg.com. Google that now and you'll see only a few hits. It's unique and therefore very findable.

But to a measure I think this question is one of opinion more than substance. I personally grew up on Forth where it was all about words, and lots of them. One learned to get very creative to save one's fingers. In the end I had about 640,000 characters, more or less in my source base. So keeping words short was important to getting work done.

Elliptical view
  • 205
  • 1
  • 7
0

I think misspellings are always a bad idea. It's just not nice on your readers. I, for one, would be wondering whether I missed something when I see the word klass. (Did they mean class, or did they mean the pirate?) At least to me, all misspellings that I recognize are irritating.

For the very few cases, where the reserved word is really the only significant thing that is known about the variable, I would use the following alternatives:

  • If it's a function argument, use aClass instead of class.

  • If it's a local or member variable, use myClass instead of class.

  • If it's an accessor, use getClass() instead of class().

Of course, the added prefix is pretty pointless, and should only ever be used as a last resort, consequently. But at least it does not interfere with the mental parser of your reader, and it's a failsafe way to avoid reserved words.

0

I think intentional misspellings or abbreviations are a good idea if used carefully and consistently.

Consider in Java:

class X { public X() { } }
X x = new X();
x.getClass;  // Wha?  How does "get" help anything?
x.class;     // Best, but requires more lexer/parser work
x.klass;     // At least as good as getClass
x.clazz;     // Same

The place to use misspellings is where the reserved word is clearly the best word for the job. There are two places not to use misspellings where you might be tempted to.

  1. You don't feel like thinking of a good name
  2. You just want a dummy variable and it doesn't need a descriptive name

In the first case, it's pretty obvious that laziness is rarely a good policy for creating quality code. In the second case, choose a really short variable. That's what mathematicians do all the time, and programmers do for indices. There's no reason to limit yourself to doing this for indices if it really is just a dummy variable:

boolean isMyName(String testName) { return myName.equals(testName); }
boolean isMyName(String s) { return myName.equals(s); }

Date nextMeeting(Klass klass) { return /* something */ }
Date nextMeeting(Klass k) { return /* something */ }

You don't lose anything with short variable names when the method or the structure of the code tells you what must be there.

Rex Kerr
  • 1,234
  • 7
  • 9
  • 2
    I'm sorry, I can't agree. How does nextMeeting work exactly? The logic is obscure. You are forcing me to look up the definition of Klass every time I'm reading your code because the name is meaningless. If instead you had nextMeeting(MeetingRoom meetingRoom), I would have one less class (klass? clazz?) definition to read and thereby be more productive. Code gets read much more than written. – MrFox Jan 07 '13 at 18:05
  • @suslik - `nextMeeting(MeetingRoom r)` is plenty. What's the `meetingRoom` getting you there? If ti was `nextMeeting(int meetingRoom)` I'd understand, but my point is _use short variable names when the information is already available from other sources_. – Rex Kerr Jan 07 '13 at 19:14
  • My post was more about the existance of Klass in the codebase. I agree with short variable names sometimes, but if your methods get long and you I have to keep srcolling up to make sure that "r" is a MeetingRoom then that isn't great either. I'm curious what the downside of meetingRoom is though? Horizontal space? Too long to type? – MrFox Jan 07 '13 at 19:19
  • @suslik - Yes, you lose horizontal context with long variable names. You lose vertical context with long methods, so it's best to try to avoid those (but I agree if you do it anyway, you probably want your variable names to be better reminders). `Klass` was an alternative _when there was a reserved word_. I don't recommend using a misspelling when the original spelling is available! – Rex Kerr Jan 07 '13 at 19:23
0

I've seen legitimate uses of Class klass when doing reflection where you do actually work with an instance of the Class class.

Matt
  • 211
  • 1
  • 8
  • 2
    The question is not whether there is any case where you have an instance, but whether you should use that spelling, or a more descriptive name such as `userClass` or some other option. – Nicole Jun 30 '11 at 21:55
  • 2
    In such case I'd prefer `classInstance` over `klass`. – Konrad Morawski Jan 14 '14 at 10:31
  • 2
    @KonradMorawski: But all object you work with are instances, so `classInstance` is pretty redundant. Moreover, I could imagine something like `class klass; Object classInstance = klass.newInstance;`. – maaartinus Jan 14 '14 at 11:48