EDIT: I really appreciate everyone’s input. I gained something from all the responses and learned a good deal about OOD.
I am making a simple virtual tabletop war game. To represent units on the battlefield I have the following simple class hierarchy: An abstract class Unit, and two derived classes, Troop and Vehicle.
I have another class that has a hashtable for all the units in the game. The hashtable values are of Unit type, so I can reference them in O(1) time.
For the most part, this is fine, but sometimes the caller NEEDS to know if something is a troop or a vehicle to call specific methods from those derived classes. To accommodate for this, I’ve created two get methods that will enforce the types:
public Troop getTroop(String uniqueID) {
Unit potentialTroop = get(uniqueID);
if(potentialTroop instanceof Vehicle) {
throw new InternalError();
}
return (Troop) potentialTroop;
}
public Vehicle getVehicle(String uniqueID) {
Unit potentialVehicle = get(uniqueID);
if(potentialVehicle instanceof Troop) {
throw new InternalError();
}
return (Vehicle) potentialVehicle;
}
(Note the class for which this belongs merely extends Hashtable, so the get method being used here is the Java’s hashtable’s get method.)
So I think this is poor OOD design because if I ever further extend unit I’m going to have to add more checks and more #get methods to this hashtable.
Am I correct in saying this? Does anyone have alternative OOD suggestions if this is the case?
Here’s a simple way to do this, not necessarily the best, but it meets these requirements:
UnitcollectionUnittypes later on, without having to add a bunch of handler methods.The solution uses a ‘template’ class to perform matching:
I made the assumption that you are going to correct your code, to not extend from
Map, but rather to encapsulate it.