Skip to content

Instantly share code, notes, and snippets.

@pavly-gerges
Last active April 8, 2023 09:18
Show Gist options
  • Save pavly-gerges/2fe95035aab7f116e868fb01a2f1305e to your computer and use it in GitHub Desktop.
Save pavly-gerges/2fe95035aab7f116e868fb01a2f1305e to your computer and use it in GitHub Desktop.
Generics in java
public class Wrapper {
private Object object;
public Wrapper(Object object) {
this.object = object;
}
public void setObject(Object object) {
this.object = object;
}
public Object getObject() {
return object;
}
}
@pavly-gerges
Copy link
Author

pavly-gerges commented Apr 8, 2023

API Design Tips

When designing your API, you should be aware of the following rules:

For class type generics and generic method type parameters:

  • Lower bounds are not allowed.
  • Instantiation of a variable of this type isn't allowed.
  • Returning a parameterized type object will restrict the implementation to utilize generics and thus won't be backward compatible.

For wildcard generics:

  • Upper bounds are used to define the type for the method returning values.
  • Lower bounds give the developer the flexibility to use the abstraction over the l-value.

Last, but not least, in order to decide the best type of boundaries to use, think of the final type-erasure you want to have on your API:

  1. Declare the type-erasure you want to finally reach.
  2. Consider optimizing your code using Type-Generics.

Here is a nice tip from the Java tutorials:

In general, if you have an API that only uses a type parameter T as an argument, its uses should take advantage of lower bounded wildcards (? super T). Conversely, if the API only returns T, you'll give your clients more flexibility by using upper bounded wildcards (? extends T).

@pavly-gerges
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment