0

Let's say I've got an abstract class called Player. Classes GameAPlayer and GameBPlayer inherit from Player. In turn, a couple of abstract classes inherit from GameAPlayer and GameBPlayer respectively.

Let's say I've got another abstract class called Engine which hosts List<Player>. Classes GameAEngine and GameBEngine both inherit from Engine. I know for a fact that all players in GameAEngine will be of type GameAPlayer, and that all players in GameBEngine will be of type GameBPlayer.

I cannot move List<Player> into GameAEngine and GameBEngine as I'm using the list in Engine itself.

Having to typecast Player into GameAPlayer and GameBPlayer every time I use the list in their respective engines just seems unclean. Is there any way I can avoid having to do this?

1
  • 1
    The simple solution is to get rid of the extra classes and add properties to the class. You are right to question your design it is unclean and ineffective. Dec 14, 2011 at 19:00

2 Answers 2

6

You are experiencing the pain of what is known as the "parallel hierarchies problem". Object-oriented languages historically have done a poor job of dealing with the parallel hierarchies problem.

There's lots of interesting discussion about this problem and how various techniques deal with it; there is no slam-dunk solution. You might start by reading this discussion:

http://lambda-the-ultimate.org/node/1621

Also, there are lots of Stack Overflow questions about this area as well.

https://stackoverflow.com/search?q=parallel+hierarchies

1
  • +1 for giving me the term for the problem. Always easier to research it further once you know exactly what you're looking for :)
    – K Mehta
    Dec 15, 2011 at 7:03
3

Change Engine to Engine<TPlayer> where TPlayer : Player.
Note that this will make base engines require generic type parameters everywhere; you can work around that using a non-generic interface.

Alternatively, make a GetPlayer method in the derived classes that does the cast, and use that instead of the base list.

1
  • The first technique makes the Engine too "Player centric". I had thought about using the second approach as well, but was trying to see if there was something better out there. I guess I'll just go that route.
    – K Mehta
    Dec 15, 2011 at 7:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.