152

In some interfaces I wrote I'd like to name generic type parameters with more than one character to make the code more readable.

Something like....

Map<Key,Value>

Instead of this...

Map<K,V>

But when it comes to methods, the type-parameters look like java-classes which is also confusing.

public void put(Key key, Value value)

This seems like Key and Value are classes. I found or thought of some notations, but nothing like a convention from Sun or a general best-practice.

Alternatives I guessed or found...

Map<KEY,VALUE>
Map<TKey,TValue>
christopheml
  • 2,444
  • 17
  • 25
chaper29
  • 1,529
  • 2
  • 10
  • 3

5 Answers5

215

Oracle recommends the following in Java Tutorials > Generics > Generic Types:

Type Parameter Naming Conventions

By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.

The most commonly used type parameter names are:

  • E - Element (used extensively by the Java Collections Framework)
  • K - Key
  • N - Number
  • T - Type
  • V - Value
  • S,U,V etc. - 2nd, 3rd, 4th types

You'll see these names used throughout the Java SE API and the rest of this lesson.

I'd stick to it to avoid the confusion among the developers and possible maintainers.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 19
    The new stream framework also uses `R` for result and `A` for accumulator. – vandale Aug 09 '14 at 15:10
  • 47
    Blech, single-letter naming. I follow this convention because convention matters more than descriptive names, but it's sad this is the best they could come up with. – warbaker Sep 09 '14 at 23:18
  • 7
    @warbaker: I find it a good way to distinguish parameterized types from actual classes. How would you otherwise tell if e.g. `Element` in `List` is a parameterized type or a class? – BalusC Sep 10 '14 at 06:10
  • 3
    It doesn't look like `BiFunction` follows this convention. If it did, it would be `BiFunction`. – michaelsnowden Jul 23 '16 at 22:54
  • 7
    Why the worry about distinguishing parameterized types from actual classes? They *are* classes. No matter what, you have to scroll up somewhere in the file to find out what they're defined as. And it'll either be an import or a parameterized type. – Vectorjohn Feb 08 '18 at 00:46
  • Funny @michaelsnowden I just happened to be looking at BiConsumer which also uses U as the second type name. – Brent Sandstrom Mar 08 '19 at 15:24
  • @Vectorjohn I agree 100%. Plus, syntax highlighting usually makes it obvious that it's a type parameter. – Drew Nutter Aug 21 '19 at 16:43
62

Append Type

A good discussion can be found in the comments on the DZone page, Naming Conventions for Parameterized Types.

See the comment by Erwin Mueller. His suggestion makes perfect obvious sense to me: Append the word Type.

Call an apple an apple, a car a car. The name in question is the name of a data type, right? (In OOP, a class essentially defines a new data type.) So call it a “Type”.

Mueller’s example, drawn from the original post’s article:

public interface ResourceAccessor < ResourceType , ArgumentType , ResultType > {
    public ResultType run ( ResourceType resource , ArgumentType argument );
}

Append T

A duplicate Question provides this Answer by Andy Thomas. Note the excerpt from Google’s style guide that suggests a multi-character type name should end in a single uppercase T.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • 9
    I like this answer. Adding "Type" is so clear and lets you have descriptive names. I'm sick of people saying, "do it because it's the convention," with no other justification. If it's a bad convention, maybe we need a new one. – Drew Nutter Aug 21 '19 at 16:38
  • A problem with simply appending the suffix "Type" is that it's also used as the suffix of many class names -- even in the standard Java library. It's not clear at a glance that it's a type parameter rather than a class name. – Andy Thomas Dec 16 '22 at 17:11
26

Yes, you can use multi-character names for type variables, as long as they are clearly distinguished from class names.

This differs from the convention suggested by Sun with the introduction of generics in 2004. However:

  • More than one convention exists.
  • Multi-character names are consistent with other Java styles, such as Google’s style for Java.
  • The readable names are (surprise!) more readable.

Readability

In some interfaces I wrote I’d like to name generic type parameter with more than one character to make the code more readable.

Readability is good.

Compare:

    public final class EventProducer<L extends IEventListener<E>,E> 
            implements IEventProducer<L,E> {

to:

    public final class EventProducer<LISTENER extends IEventListener<EVENT>,EVENT> 
           implements IEventProducer<LISTENER, EVENT> {

or, with Google’s multi-character convention:

    public final class EventProducer<ListenerT extends IEventListener<EventT>,EventT> 
           implements IEventProducer<ListenerT, EventT> {

    public final class EventProducer<ListenerT extends IEventListener<EventT>,EventT> 
           implements IEventProducer<ListenerT, EventT> {

Google style

The Google Java Style Guide allows both single-letter names and multi-character class-like names ending in T.

5.2.8 Type variable names

Each type variable is named in one of two styles:

  • A single capital letter, optionally followed by a single numeral (such as E, T, X, T2)

  • A name in the form used for classes (see Section 5.2.2, Class names), followed by the capital letter T (examples: RequestT, FooBarT).

Issues

“Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.” – from the Oracle tutorials, “Generic types”

Single-character names are not the only way to distinguish type parameters from class names, as we’ve seen above.

Why not just document the type parameter meaning in the JavaDoc?

It’s true that the @param JavaDoc elements can provide a longer description. But it’s also true that the JavaDocs are not necessarily visible. (For example, there’s a content assist in Eclipse that shows the type parameter names.)

Multi-character type parameter names don’t follow the Oracle convention!

Many of Sun’s original conventions are followed nearly universally in Java programming.

However, this particular convention is not.

The best choice among competing conventions is a matter of opinion. The consequences of choosing a convention other than Oracle’s in this case are minor. You and your team can choose a convention that best meets your needs.

Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
16

You can use javadoc to at least give users of your generic class a clue. I still don't like it (I agree with @chaper29) but the docs help.

eg,

/**
 * 
 * @param <R> - row
 * @param <C> - column
 * @param <E> - cell element
 */
public class GenericTable<R, C, E> {

}

The other thing I have been known to do is use my IDE to refactor a class breaking the convention. Then work on the code and refactor back to single letters. Makes it easier for me anyway if many type parameters are used.

Tom Carchrae
  • 6,398
  • 2
  • 37
  • 36
  • 2
    I'd say Javadoc comments for type parameters are usually a must. – migu Apr 07 '17 at 06:42
  • `R` can be considered a "result" of a function, `E` for DOM "element" indeed, and `C` for some "callback", "context", or "constructor". What if "RowT", "ColumnT", and "CellElementT"? – Artfaith Aug 31 '23 at 13:28
16

The reason why the official naming convention reccommends using single letter is the following:

Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.

I think with modern IDEs that reason is no longer valid as eg. IntelliJ Idea shows generic type parameters with different colors than regular classes.

Code with generic type as displayed in IntelliJ Idea 2016.1 Code with generic type as displayed in IntelliJ Idea 2016.1

Because of that distinction I use longer descriptive names for my generic types, with same convention as regular types. I avoid adding prefixes and suffixes such as T or Type as I consider them unnecessary noise and no longer needed to visually distinguish generic types.

Note: As I am not a user of Eclipse or Netbeans, I do not know whether they offers a similliar feature.

Vojtech Ruzicka
  • 16,384
  • 15
  • 63
  • 66
  • 1
    I wouldn't base naming conventions around assumed capabilities of the tools each person ever reading/modifying that same file will have. I personally like to use a text editor for my coding (Sublime Text) which is not an IDE. Text editors usually nowadays have syntax coloring, but not deep understanding of the underlying code structure which I think would be required to color type variable names correctly. And basing this argument on the color is inherently exclusive to people with poor color vision (I am part of the 8 % of males with red-green color blindness) – joonas.fi May 09 '18 at 10:30
  • 1
    Good point regarding people with poor color vision. Regarding not using IDEs - if people prefer using simple text editors, it is fine, but they voluntarily sacrifice features IDEs offer to them in favor of more lightweight tool. This may be just one of those features missing. In the end though, if a descriptive name is used instead of a single letter, you should be able to tell the meaning based on the name without an IDE and without the color coding. Color coding just makes this faster. – Vojtech Ruzicka May 14 '18 at 14:24
  • Eclipse doesnt colour highlight generic types, but it does show the javadoc for them on mouseover where they occur, so a class defined `/** @param Some parameter or other */public class Foo { public U getValue(){ return null;}}` (obviously that's a useless example!) will show 'U extends Number' as the heading and 'Some parameter or other' in the body in the pop-up javadoc window when you hover over the `U` of the `getValue()` method return type – SteveR Aug 17 '21 at 14:29