I use generics quite extensively at work with Java collections and Guava. I understand it fairly well when using the APIs:
However, I find it difficult to come up APIs using generics. Are there design patterns for Java generics? Or any references to Java generics would also help. I've read:
I'm familiar with just two patterns where generics are useful:
Optional<T>
, etc.Predicate<T>
, Function<T>
Most standard design patterns are about the ad-hoc polymorphism inherent in standard OO with inheritance and composition. Generics are about parametric polymorphism. Your second "pattern" basically subsumes the entire concept, so I wouldn't call that a pattern.
So what are the parametric patterns?
How about the Lender pattern. It is not important what what type of resource is lent or borrowed, so that can be a generic parameter.
Factory can also be expressed using generics. The type of instances being produced is a parameter.
Functional or callback objects usually come in void and T
-returning flavors.
Is that the level of abstraction you are asking for?
I'll keep editing this answer as I come up with more.
As far as APIs go, my rule of thumb is to try and accept the most expansive type possible, meaning essentially as many wildcards as possible in the method arguments, using variance to decide if extends
or super
is appropriate, and return the most specific type possible, meaning as few type variables or wildcards as possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With