Generics with constraints hierarchy

Posted by devoured elysium on Stack Overflow See other posts from Stack Overflow or by devoured elysium
Published on 2010-05-22T01:08:25Z Indexed on 2010/05/22 1:10 UTC
Read the original article Hit count: 427

I am currently facing a very disturbing problem:

interface IStateSpace<Position, Value>
where Position : IPosition           // <-- Problem starts here
where Value : IValue                 // <-- and here as I don't
{                                    //     know how to get away this
                                     //     circular dependency!
                                     //     Notice how I should be
                                     //     defining generics parameters
                                     //     here but I can't!
    Value GetStateAt(Position position);
    void SetStateAt(Position position, State state);
}

As you'll down here, both IPosition, IValue and IState depend on each other. How am I supposed to get away with this? I can't think of any other design that will circumvent this circular dependency and still describes exactly what I want to do!

interface IState<StateSpace, Value>
where StateSpace : IStateSpace
where Value : IValue
{
    StateSpace StateSpace { get; };
    Value Value { get; set; }
}

interface IPosition
{
}

interface IValue<State>
where State : IState {
    State State { get; }
}

Basically I have a state space IStateSpace that has states IState inside. Their position in the state space is given by an IPosition. Each state then has one (or more) values IValue. I am simplifying the hierarchy, as it's a bit more complex than described. The idea of having this hierarchy defined with generics is to allow for different implementations of the same concepts (an IStateSpace will be implemented both as a matrix as an graph, etc).

Would can I get away with this? How do you generally solve this kind of problems? Which kind of designs are used in these cases?

Thanks

© Stack Overflow or respective owner

Related posts about generics

Related posts about object-oriented-design