vendredi 27 novembre 2015

How to model similar but not exact data in object oriented paradigm?

I have an interface and two data sources that populate concrete instances of objects that implement the interface. The interface exposes methods that only one of the two instances can satisfy in a meaningful way.

public interface IFoo {
    public int getValueA();
    public int getValueB();
}

public FooFromFile implements IFoo {
    int a;
    int b;
    ...
    public int getValueA() {
        return a;
    }
    public int getValueB() {
        return b;
    }
}

public FooFromNetwork implements IFoo {
    int a;
    ...
    public int getValueA() {
        return a;
    }
    public int getValueB() {
        return 0; // return 0 because FooFromNetwork never gets value b.
    }
}

Every code base I've worked on has code like this and I find it usually stems from a desire to apply 'is-a' relationships where something else may be more appropriate. I have some time to refactor the code base on which I am currently working. What would be some good modeling solutions for situations like this? The actual code is much more complicated than this but solving the toy issue here, with a robust pattern that scales, would go a long way.

Aucun commentaire:

Enregistrer un commentaire