mercredi 4 avril 2018

POJOs, generics and extending them

I have a POJO that returns some value, but now that value could be of a different type:

public class ContainerA {
    String value;
    public ContainerA(String value) {
       this.value = value;
    }
    public String getValue() {
       return value;
    }
    //some more methods
}

So I wanted to just replace it with this other one, but the refactoring effort would be just too great:

public class ContainerA<T> {
    T value;
    public ContainerA(T value) {
       this.value = value;
    }
    public T getValue() {
       return value;
    }
    //some more methods
}

And to avoid that large refactoring I was thinking that I could have something like this:

public interface Container<T> {
    public T getValue() {
    //some more methods
}

public class ContainerA implements Container<String> {
    String value;
    public ContainerA(String value) {
       this.value = value;
    }
    public String getValue() {
       return value;
    }
    //implementation of those other methods
}

But since most of those POJO classes will look pretty much the same and there are a bunch of other methods, so I was wondering why this would be problematic:

public class Container<T> {
    T value;
    public Container(T value) {
        this.value = value;
    }
    public T getValue() {
        return value;
    }
    //some other methods
}

public class ContainerA extends Container<String> {
    public ContainerA(String value) {
       super(value);
    }
}

I've never seen a solution like that, which is why it looks suspicious to me. Is there a better approach? is any of the above ok? why?

Aucun commentaire:

Enregistrer un commentaire