I'm trying to design some interfaces for a library that will support multiple storage systems for it's data - like mysql, or mongo.
I'm trying to design a single Model interface so that anyone using my API can see what data is available. The problem is that the ID or primary key type varies. For example from mysql it'll be a Long and mongo uses ObjectId, etc.
I was thinking I could handle this with generics, but I'm not sure this is the right approach. I don't want to have to cast all the time to get the right ID types.
Is this an acceptable approach or should I be using something else? I don't want to build my APIs with this approach and then run into issues and have to redo it all.
The dog model interface:
public interface DogModel<T> {
T getId();
}
The sql-specific dog model:
public class SqlDogModel implements DogModel<Long> {
private final Long id;
public SqlDogModel(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
}
How I declare the model in the general storage interface:
public interface StorageAdapter {
Optional<DogModel> getDog(String name);
}
StorageAdapteralso needs to be generic:StorageAdapter<T>. If you don't want that, then perhaps rethink your premise.