0

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);
}
4
  • Your StorageAdapter also needs to be generic: StorageAdapter<T>. If you don't want that, then perhaps rethink your premise. Commented Jul 1, 2021 at 2:20
  • Ah, that does work. It's compiling anyway, whether that's a good approach is unclear. Commented Jul 1, 2021 at 2:29
  • Perhaps you should define what you mean by "good". Commented Jul 1, 2021 at 2:30
  • Not sure, simpler? Not misusing the language somehow, java pros looking at it and laughing. Commented Jul 1, 2021 at 5:19

1 Answer 1

1

It can be made simpler: An abstract class can implement an interface, but in my example I have the getter and setter logic in the base class and this can't happen in the interface as interfaces don't have logic.

public abstract class DogModel < T > {
T id;
public T getId() {
    return id;
}
public void setId(T id) {
    this.id = id;
}}

public class SqlDogModel extends DogModel < Long > {}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.