Now and then in my code I find that I can solve a problem by either using a naked generic class or one with wildcards.
I have a design where a class like this:
Class World<T, C> { .... }
definitely in general is making my code cleaner than it would have been without generics.
Yet, sometimes I use
World theWorld;
or sometimes I end up with
World<?, ?> theWorld;
I do this because it seems to be what it takes to make the compiler accept it and my
attempts to avoid them lead me to more casting or inheriting complexity.
It looks ugly and smelly to me and yet I cannot justify the added complexity it looks like I need to introduce to avoid it.
What are some cases (if any) that you believe using a naked or wildcarded generic is acceptable idiomatic Java?
Any time you could use generics but don’t need it in that specific situation.
<?>tells the compiler roughly: “I know about generics, but I don’t need the type now”.Maybe the type is needed in other situation. E.g. if you have a
Setthat just stores anything, like a cache, and you just don’t care for the type of the elements at all. At other times you do, when you process specific elements.It smells if you use too loosely bound type parameters (like
<?>which is quite loose) but try to determine the type afterwards, e.g. withinstanceofor some custom type discriminator. Then something was designed poorly.