Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long (readable) names in Generics/Templates

I find myself sometimes writing code that looks like this with Java Generics:

/**Class description
 *@param <K> Key to '.....'
 public class Mappy<K>{
   ///class methods, fields, etc....
 }

Sometimes using single-character names has caused slowdowns when months later I return to code and have to keep scrolling up to remember what "T" & "E" are. But last I checked, Oracle's official guideline was single-character names and I've never seen a java programmer not do it.

In C#, using TDescription is part of the official style guidelines, similar to how Google & others use Ixxxx for interfaces. But I still see one-letter names in production code & APIs for C#. I've heard it is similar in C++. In Haskell & Ocaml, especially Haskell, you use 'a' or 'b' as a generic parameter in your function signature (forget if the compiler/interpreter forces this or if they can be multi-letter).

I'm just asking this 'question' to see how y'all do it: do you stick with single-letter names in your generics/templates/etc..., do you have a convention like Txxx, do you give them full-fledged names (and does that confuse co-workers), or do you do something else?

This is very similar to Breaking java generics naming convention? (which I found via google). Instead of poking that question, I just wanted to gather some modern opinions (see if there's been a style coup in the pass two and a half years).

Edit 1:

Probably the reason this question came up is that a few days ago I made a pledge to dump the variable 'i'. Too many times using the quick & dirty loop variable 'i' has caused issues in nested loops & refactoring so I decided to go with only full-fledged names.

like image 463
Lan Avatar asked Feb 14 '26 05:02

Lan


2 Answers

Naming conventions exist as a tool to help you maintain readable code.

They are there to help you. They are not a rule.
There's a higher value to have easy to read - maintainable code than to blindly follow a naming convention.

like image 183
Yochai Timmer Avatar answered Feb 15 '26 18:02

Yochai Timmer


I use single-letter uppercase types in my generics when the type can be (almost) any type. Like with Map<K,V> etc.

However, when the type has more meaning than just ANY type, such as:

public class Table<Column extends Enum<Column> & Table.Columns> {
 ...
 public interface Columns {
  ...

I use a more appropriate name Column but retain the convention of the initial uppercase. I feel it is important to maintain brevity for types as you are likely to use it many times in the code. A single uppercase character is - you must admit - perfect brevity.

like image 38
OldCurmudgeon Avatar answered Feb 15 '26 18:02

OldCurmudgeon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!