Coming from a C and C++ background, I found judicious use of typedef
to be incredibly helpful. Do you know of a way to achieve similar functionality in Java, whether that be a Java mechanism, pattern, or some other effective way you have used?
12 Answers
Java has primitive types, objects and arrays and that's it. No typedefs.
-
47
-
81@TomášZato I don't know most people, but in my experience, it's useful for adding semantics like:
typedef int PlayerID
which enables the compiler to make sure PlayerIDs aren't being used interchangeably with other ints, and it also makes code much more readable for humans. Basically, it's like an enum but without a limited set of values.– weberc2Jan 2, 2015 at 23:43 -
94@TomášZato It's also usefull to shorten long types such as
typedef MegaLongTemplateClass<With, Many, Params> IsShorten;
. Feb 20, 2015 at 12:47 -
41@weberc2 "which enables the compiler to make sure PlayerIDs aren't being used interchangeably with other ints" –
typedef
doesn't enable any such thing. It just gives another name for a type. Dec 16, 2015 at 8:24 -
14Also useful if, for instance, you have some ID of type
int
and you need to change it tolong
, you have to change it in every place in code where you work with the ID. If you hadtypedef
, you'd only have to change it in 1 place.– JardoJan 2, 2018 at 10:15
If this is what you mean, you can simply extend the class you would like to typedef, e.g.:
public class MyMap extends HashMap<String, String> {}
-
7I'd argue whether this is any more anti-pattern than using typedef in C.– ZedJul 28, 2009 at 16:41
-
23It definitely is -
typedef
has none of the problems that article describes for those fake classes (and they are very real). Jul 28, 2009 at 17:01 -
30@Andreas_D: your link, fixed: ibm.com/developerworks/java/library/j-jtp02216/index.html Jan 11, 2013 at 22:53
-
8I like this for the same reason I like typedefs. If you have a container of objects, it is easy to swap container types by changing the typedef. Also, it can abstract the container to the end user (which is sometimes desirable). I would usually do this inside of another class, so then the type becomes more obvious (i.e. MyTree.Branches, where class Branches extends HashSet<MyTree>{}) Oct 6, 2013 at 16:13
-
11Although the main problem with this approach is that you can't use it with
final
classes. Apr 8, 2014 at 21:24
There is no typedef in java as of 1.6, what you can do is make a wrapper class for what you want since you can't subclass final classes (Integer, Double, etc)
-
7The referenced anti-pattern article is based on the assumption that you just want to shorten your typing (which would actually hide the helpful type information). The real use most people want is to disambiguate types and let the compiler do its job for you. See IndexT above. public Invoice fetchInvoiceItem(String, String, String); versus public Invoice fetchInvoiceItem(CustomerId, InvoiceId, InvoiceLineItemId); Explicit types plus Converters/Validators makes programming Web APIs where EVERYTHING starts out as a String a lot safer. Jan 13, 2017 at 14:42
-
2
As others have mentioned before,
There is no typedef mechanism in Java.
I also do not support "fake classes" in general, but there should not be a general strict rule of thumb here:
If your code for example uses over and over and over a "generic based type" for example:
Map<String, List<Integer>>
You should definitely consider having a subclass for that purpose.
Another approach one can consider, is for example to have in your code a deceleration like:
//@Alias Map<String, List<Integer>> NameToNumbers;
And then use in your code NameToNumbers and have a pre compiler task (ANT/Gradle/Maven) to process and generate relevant java code.
I know that to some of the readers of this answer this might sound strange, but this is how many frameworks implemented "annotations" prior to JDK 5, this is what project lombok is doing and other frameworks.
Really, the only use of typedef that carries over to Javaland is aliasing- that is, giving the same class multiple names. That is, you've got a class "A" and you want "B" to refer to the same thing. In C++, you'd be doing "typedef B A;"
Unfortunately, they just don't support it. However, if you control all the types involved you CAN pull a nasty hack at the library level- you either extend B from A or have B implement A.
-
15Having
typedef
would also be useful to create aliases for invocations of generic types. For example:typedef A<Long,String> B;
(this may be a special case of what you've described, but it shows the appeal of the idea a little more clearly).– igorrsMay 11, 2012 at 0:24 -
In my use case, I want to give aliases to primitive types.
real_t
fordouble
andbool
forboolean
. Aug 31, 2018 at 5:27
Perhaps this could be another possible replace :
@Data
public class MyMap {
@Delegate //lombok
private HashMap<String, String> value;
}
-
2Don't you think that this now has a problem because whenever you define
myMap
instance of typeMyMap
, you can operate on actual HashMap only by typingmyMapInstance.value.SomeOperation()
instead ofmyMapInstance.SomeOperation()
. This is annoying, isn't it? Nov 17, 2016 at 22:02 -
3you can still do myMapInstance.SomeOperation() - this is what the @Delegate is for Jan 17, 2018 at 16:46
-
Note that currently (8/2020) @Delegate is "experimental" in lombok projectlombok.org/features/experimental/Delegate
Current status: negative - Currently we feel this feature will not move out of experimental status anytime soon, and support for this feature may be dropped ...
Aug 17, 2020 at 13:38
As noted in other answers, you should avoid the pseudo-typedef antipattern. However, typedefs are still useful even if that is not the way to achieve them. You want to distinguish between different abstract types that have the same Java representation. You don't want to mix up strings that are passwords with those that are street addresses, or integers that represent an offset with those that represent an absolute value.
The Checker Framework enables you to define a typedef in a backward-compatible way. It works even for primitive classes such as int
and final classes such as String
. It has no run-time overhead and does not break equality tests.
Section Type aliases and typedefs in the Checker Framework manual describes several ways to create typedefs, depending on your needs.
Kotlin supports type aliases https://kotlinlang.org/docs/reference/type-aliases.html. You can rename types and function types.
-
So do several other languages, however, OP asked about Java, so this answer is not relevant Mar 11, 2022 at 15:01
In some cases, a binding annotation may be just what you're looking for:
https://github.com/google/guice/wiki/BindingAnnotations
Or if you don't want to depend on Guice, just a regular annotation might do.
You could use an Enum, although that's semantically a bit different than a typedef in that it only allows a restricted set of values. Another possible solution is a named wrapper class, e.g.
public class Apple {
public Apple(Integer i){this.i=i; }
}
but that seems way more clunky, especially given that it's not clear from the code that the class has no other function than as an alias.
Typedef allows items to be implicitly assigned to types they are not. Some people try to get around this with extensions; read here at IBM for an explanation of why this is a bad idea.
Edit: While strong type inference is a useful thing, I don't think (and hope we won't) see typedef
rearing it's ugly head in managed languages (ever?).
Edit 2: In C#, you can use a using statement like this at the top of a source file. It's used so you don't have to do the second item shown. The only time you see the name change is when a scope introduces a name collision between two types. The renaming is limited to one file, outside of which every variable/parameter type which used it is known by its full name.
using Path = System.IO.Path;
using System.IO;
-
24"Typedef allows items to be implicitly assigned to types they are not" What? Typedef simply allows you to create another name as an alias for the type. The type is still the exact same, you just get a shorter name for it. It has nothing to do with type inference. -1– jalfJul 28, 2009 at 16:34
-
@jalf: Actually, type inference is used as the solution to exactly what you're talking about, but I've given another example where you can use a "typedef" to get around a name collision. Jul 28, 2009 at 16:50
-
1updated link: ibm.com/developerworks/java/library/j-jtp02216/index.html Aug 2, 2011 at 3:48
-
@AlexanderMalakhov Thanks, I went ahead and updated the answer with your link Jul 2, 2012 at 12:45
There is no need for typedef in Java. Everything is an Object except for the primitives. There are no pointers, only references. The scenarios where you normally would use typedefs are instances in which you create objects instead.
-
22No, the need for typedef still exists if you want a shorter name for a type. Or just if you want to be able to replace the use of one type with another by changing one place in the source code.– jalfJul 28, 2009 at 16:36
-
31@Bill K: meh, say that after you've had to type something like std::map<int, std::map<std::string, boost::shared_ptr<std::string> > >::const_iterator a few times. In that case, a name-shortening typedef enhances readability, not hinders it.– JoelJul 30, 2009 at 14:45
-
26Renaming a type can improve readability drastically. What is easier to read and comprehend (and thus more readable:)
UnmodifiableDirectedGraph<IncrediblyFancyEdgeType, IncrediblyFancyAbstractNode.EvenFancierConcreteNode>
orIncrediblyFancyGraph
? I can always refer to the definition to find out what it's actually about. That way I can also be sure I won't missUnmodifiableDirectedGraph<IncrediblyFancyEdge,IncredilyFancyAbstractNode.SlightlyLessFancyConcreteNode>
out of sheer boredom. Mar 3, 2011 at 21:31 -
11@AleksandarDimitrov I know that your comment is almost 3 years old as I type this, but I feel it's very important to point out how contrived and unrealistic that example is: none of those class names contains the word
Enterprise
.– CaseyFeb 18, 2014 at 15:22 -
5Bad names hinder readability. Good names help. Typedefs can help if there is full name is so long that it becomes hard to read or screws up your code formatting. It also would help when interacting with someone else's poorly choosen or ambiguous class names. If you really believe that a typedef is inherently going to make your code unreadable, then you should also believe that you should never use import statements and should always refer to fully qualified class names. Mar 4, 2014 at 16:07
public interface ScopeFactory { <Scope extends Map<String, Object>> Scope create(...) throws Exception; }