When should I use the JAVA generic interface design?
I have some interfaces that I intend third-parties to implement in the future, and I provide a base implementation myself. I'll only be using a couple to show the example.
Currently, they are defined as
Item:
public interface Item {
String getId();
String getName();
}
ItemStack:
public interface ItemStackFactory {
ItemStack createItemStack(Item item, int quantity);
}
ItemStackContainer:
public interface ItemStackContainer {
default void add(ItemStack stack) {
add(stack, 1);
}
void add(ItemStack stack, int quantity);
}
Now, Item and ItemStackFactory I can absolutely foresee some third-party needing to extend it in the future. ItemStackContainer could also be extended in the future, but not in ways that I can foresee, outside my provided default implementation.
Now, I'm trying to make this library as robust as possible; this is still in the early-stages (pre-pre-alpha) so this may be an act of over engineering (YAGNI). Is this an appropriate place to use generics?
You use the JAVA generic interface when your implementation is likely to be generic as well.
For example, any data structure that can accept arbitrary objects is a good candidate for a generic interface. Examples: List and Dictionary.
Any situation where you want to improve type safety in a generalised way is a good candidate for generics. A List is a list that only operates on strings.
Any situation where you want to apply SRP in a generalised way and avoid type-specific methods is a good candidate for generics. For example, a PersonDocument, PlaceDocument and ThingDocument can be replaced with a Document.
The Abstract Factory pattern is a good use case for a generic, while an ordinary Factory Method would simply create objects that inherit from a common, concrete interface.