So I’m stumped as to whether there’s an easier, cleaner way to do the following…
I have a project with types that are similar in concept to the following:
So far so good, but here’s where it gets ugly…
…and using the Zoo would require code like this:
That’s atrocious! How can this be made simpler and/or cleaner?
Hard constraints:
The Tiger and TigerTag types cannot be combined — they MUST be separate types, b/c…
They serve different purposes with discrete concerns, but they are associated;
They must not pollute each other with their concerns -(the Tag is embedded);
EDIT: Tags and Animals must be kept in separate assemblies. Assembly containing Animal types has a dependency on assembly containing Tag types.
Please focus on suggestions that meet the above-stated constraints, if at all possible.
Thanks.
EDIT: I just want to clarify what I find ugly: It’s the bit about having to specify two generic type parameters (T and U) for the ProcessAnimal method declaration (and call). I just want to specify the T for the IAnimal<U>. Is that possible?
Why isn’t the Tag class generic:
Thanks for the reply.
My apologies for not including this in the original constraints, but I’ve updated the post now.
The desired model is for the Tag types to not have any dependencies on the Animal types, and that they be encapsulated by (embedded in) the Animal types. Following your suggestion would allow for the encapsulation, but it would create a dependency on the Animal type(s). This is not desirable for various reasons but mainly independence from the ‘animals’, if you’ll pardon the pun 😉
Instead of ITigerTag use ITagData<T>.
You can have both a generic & non-generic interface.
What’s the type constraint for T?
If it’s IAnimal then it would have the same issue as u/WetSound‘s suggestion above.
How about editing signature for ProcessAnimal?
void ProcessAnimal<U>(IAnimal<U> t) where U : ITagData { … }
Then I think compiler should be able to infer U from the passed argument and you could just write zoo.ProcessAnimal(tiger) without explicitly specifying U.