Generic type parameter naming convention for Java (with multiple chars)? Generic type parameter naming convention for Java (with multiple chars)? java java

Generic type parameter naming convention for Java (with multiple chars)?


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.


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.


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.