Java generic type parameter naming convention scope
The second is certainly more conventional. The first pattern won't hold up if you have a large utility class with generic methods.
We can see examples of this here in openjdk, and in popular libraries like this guava class. Note they both re-use T as a type variable in most methods. This allows other identifiers like E, K, V, etc to retain some semantic meaning.
Where does the T, U, V convention for generic type params come from?
In the standard Java SE API's, the designer have typically chosen a one-letter identifier that is related to the meaning / purpose of the type parameter:
Iterator<T>
- javadoc whereT
means type. Other examples areListIterator<T>
,Iterable<T>
,Comparable<T>
,Comparator<T>
andClass<T>
.Collection<E>
- javadoc whereE
means element. Various other collection classes and interfaces useE
.Map<K,V>
- javadoc whereK
means key, andV
means value.Enum<E>
- javadoc whereE
means enum.
These tend to disprove your assertion that there is a general (widespread) T
, U
, V
convention, at least for Java. Obviously, in the absence of specific guidance, some individual designers will adopt what is an obvious extension to the guidance to use T
(see links below) but that would appear to be a result of individual choice. (And the groups probably would have treated this as not worthy of discussion.)
(If you want to do an exhaustive search, visit each of the javadocs index A-Z pages, and search them for all occurrences of "<".)
I'm hoping for a link to an old discussion/commit/mailing list where the convention was first discussed.
In the case of Java, I doubt that you will find this. The discussions and mailing lists would have been private, and the Java source code was still closed when generics were added to the language, along with all of the examples above.
@Lew Bloch has found a few examples (see below) of T
, U
, V
in the APIs added to Java SE in Java 8 as part of the streams support. I assert that this does not prove a general pattern, and the large number of preexisting classes disprove it.
Other negative evidence of a general pattern or convention:
- http://cr.openjdk.java.net/~alundblad/styleguide/index-v6.html#toc-type-variables which doesn't mention
U
andV
. - http://docs.oracle.com/javase/tutorial/java/generics/types.html which recommends use of
S
,U
andV
as 2nd, 3rd and 4th type parameters. (NotU
,V
,W
...)
Finally, the JLS (JLS 6.1) recommends:
Type variable names should be pithy (single character if possible) yet evocative, and should not include lower case letters. This makes it easy to distinguish type parameters from ordinary classes and interfaces.
Container types should use the name
E
for their element type. Maps should useK
for the type of their keys andV
for the type of their values. The nameX
should be used for arbitrary exception types. We useT
for type, whenever there is not anything more specific about the type to distinguish it. (This is often the case in generic methods.)If there are multiple type parameters that denote arbitrary types, one should use letters that neighbor
T
in the alphabet, such asS
. Alternately, it is acceptable to use numeric subscripts (e.g.,T1
,T2
) to distinguish among the different type variables. In such cases, all the variables with the same prefix should be subscripted.
In short, U
and V
are not explicitly mentioned in the JLS, but other alternatives are.
Breaking java generics naming convention?
I am beginning to disagree with the single-character convention, after using it since the mid-1990s.
I find the readable names more readable. This is helpful in understanding both the implementation and interface of generic types.
The ambiguity problem seems overstated for Java. Few class names are all-uppercase. Constants are not used in the same context as class names.
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.)
For example, 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> {
Although the single-character names have been recommended as a convention by Sun/Oracle, conventions can be changed. The consequences of challenging this convention are minor. If you and your team prefer meaningful names for your type parameters, I personally would go for it.
Edit (2015)
Google style for Java 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).
Difference between V, T and E in Java
Java has a feature called generics which is used to develop classes such that its functionality can be used with any type of objects. The letter you see like T
, E
or V
are just place holders. For example List<E>
. This is substituted with actual class when start using the list like below.
List<Integer> numbers = new ArrayList<Integer>();
Java uses this approach to check type safety so that a String
object cannot be added to an Integer
list.
numbers.add(1); //Good
numbers.add("Harry"); //Compilation error
Here are some useful resources.
- https://docs.oracle.com/javase/tutorial/java/generics/index.html
- https://www.baeldung.com/java-generics
Is there a naming convention for the type parameter in generic typed code (bracy flavoured)
A widely adopted standard is T1
, T2
, T3
, etc, if there is more than 1 unpurposed generic type parameter (that is, where the intended purpose of the parameters is not known from within the class itself, so you can't really give them a more descriptive name).
See Tuple
class, as a good example here.
Tuple
has the following forms:
Tuple<T1>
Tuple<T1, T2>
Tuple<T1, T2, T3>
Tuple<T1, T2, T3, T4>
Tuple<T1, T2, T3, T4, T5>
Tuple<T1, T2, T3, T4, T5, T6>
Tuple<T1, T2, T3, T4, T5, T6, T7>
Using anything else in cases like this will probably be confusing to anyone reading your code. On seeing T1
, T2
, T3
, everyone will know they are generic type parameters.
However, in the case of generic parameters with predefined purposes, specific names are more appropriate. As pointed out by @AlexeiLevenkov, for return values it's also very common to use TResult
to distinguish it from any other type arguments. Func
provides a good example of this, as described in the documentation here, with example below:
public delegate TResult Func<in T, out TResult>(
T arg
)
Along similar lines, Dictionary
uses <TKey, TValue>
as its type parameters. That's because it needs to be immediately clear which is which. The class code doesn't know what TKey
or TValue
are, but it does know they represent keys and values, so it make sense to put that information in the parameter name.
Microsoft have some (old!) naming guidelines here, where they cover another interesting case. They suggest indicating constraints placed on a type parameter in the name of the parameter itself, as follows:
public interface ISessionChannel<TSession> where TSession : ISession
{
TSession Session { get; }
}
In this case, because the generic parameter is constrained to be an ISession
, it makes sense to communicate this by naming the parameter TSession
.
Understanding Java generics. Type parameter conventions
Some examples:
Map<K, V>
: A map usually assignsV
alues toK
eys. These are special kinds of types, so they are used here.List<E>
: A list containsE
lements. It's a convention that they are called elements. On the other hand,T
would also be acceptable here.Formatter<T>
: A formatter can format anyT
ype. It's not really an element, nor a key, nor a value, soT
is the correct letter here.Triplet<T, U, V>
: A triplet for arbitrary types. Since the type definition does not know anything about the types that will be filled in later, it uses just theT
for the first type, followed by the next letters in alphabetical order.
Related Topics
How to Remove Leading Zeros from Alphanumeric Text
How to Disable Jsessionid in Tomcat Servlet
Java Simpledateformat for Time Zone with a Colon Separator
How to Set Dpi Information in an Image
How to Convert Binary String Value to Decimal
Checking If a String Is Empty or Null in Java
How to Read Numeric Strings in Excel Cells as String (Not Numbers)
Java Properties Utf-8 Encoding in Eclipse
Httpurlconnection Invalid Http Method: Patch
Should Private Helper Methods Be Static If They Can Be Static
Static Versus Non-Static Lock Object in Synchronized Block
Delete Item from Array and Shrink Array
How to Add Unique Jcomboboxes to a Column in a Jtable (Java)