Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for patterns and API design with Java generics

I use generics quite extensively at work with Java collections and Guava. I understand it fairly well when using the APIs:

  1. PECS rule
  2. {co, contra, in}variance
  3. Wildcard
  4. Bounded generics

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:

  1. Effective Java
  2. The book 'Java Generics and Collections'
  3. http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html

I'm familiar with just two patterns where generics are useful:

  1. Concept of containment: Java collections, Guava Optional<T>, etc.
  2. Type parameterization: Guava Predicate<T>, Function<T>
like image 258
Abs Avatar asked Nov 01 '22 12:11

Abs


1 Answers

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.

like image 183
2 revs Avatar answered Nov 15 '22 04:11

2 revs