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 //problem
where Value : IValue //problem
{
StateSpace StateSpace { get; };
Value Value { get; set; }
}
interface IPosition
{
}
interface IValue<State>
where State : IState { //here we have the problem again
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
It’s not entirely clear what the problem is – yes, you’ve got circular dependencies in your generic types, but that works.
I have a similar “problem” in Protocol Buffers: I have “messages” and “builders”, and they come in pairs. So the interfaces look like this:
and
It’s certainly ugly, but it works. What do you want to be able to express that you can’t currently express? You can see some of my thoughts about this on my blog. (Parts 2 and 3 of the series about Protocol Buffers are the most relevant here.)
(As an aside, it would make your code more conventional if you would add a
Tprefix to your type parameters. Currently it looks likeStateandValueare just classes.)