mardi 8 décembre 2015

Generic design for custom Table

Forgive me if there are syntax problems. The goal of this is not to get the code perfect but to get the design.

I have an interface ITable<T>

public interface ITable<T> {
    public Collection<T> getEntries();
    public void add(CustomObj value);
    public Collection<CustomObj> getCustomObjects();
}

that is used by two classes:

TableOne<CustomObj> and TableTwo<Pair<CustomObj, CustomObj>>

Then I have an interface that applies these tables using a function

public interface ITableFunction<T> {
    public abstract Collection<ITable<?>> execute(Collection<ITable<T>> tables);
}

My dilemma occurs when I try to create a generic Abstract class

public abstract class AbstractTableFunctionCombined<T> implements ITableFunction<T>{
    private boolean someBool;
    public AbstractTableFunctionCombined(boolean someBool){
        this.someBool = someBool;
    }
    @Override
    public Collection<ITable<?>> execute(Collection<ITable<T>> tables){
        // What i would like to do, but can't right now:
        ITable<T> combinedTable;
        if (someBool){
            combinedTable = new TableOne();
        } else {
            combinedTable = new TableTwo();
        }
        for(ITable<T> table : tables){
            combinedTable.addAll(table.getCustomObjects());
        }
        for(T entry : table.getEntries()){
            execute(entry);
        }
    }
    public abstract void execute(T entry);

}

The issue is that I can't guarantee that the type T is the same as the table that I'm trying to instantiate. I thought I had to create some kind of relationship from the Pair<CustomObj, CustomObj> and the regular CustomObj. I tried creating a Entry interface that these both would use, and having ITable<T> be ITable<T extends Entry> but again this runs into the same problem.

I also thought that maybe I can make the TableOne and TableTwo classes use the same Generic i.e. TableTwo<T> implements ITable<T>, but TableTwo has a hard restriction of using Pair<CustomObj, CustomObj>.

Would I have to create two separate classes: AbstractTableFunctionOne<CustomObj> and AbstractTableFunctionTwo<Pair<CustomObj, CustomObj>> ? I would like to avoid this as it would be a lot of duplicated code.

Or am I over forcing this Object oriented design? Should TableOne and TableTwo not even implement the same interface?

Aucun commentaire:

Enregistrer un commentaire