Reputation: 7951
I am reading now the book "Head First OOA&D". There are examples of code. I have a problem with accepting the next solution:
If there is a hierarchy of entities in the system, there is proposed to use a map of properties instead of writing an entire tree of classes.
For example: Unit with map of properties:
public class Unit {
private UnitType type;
private Map<String, Object> properties;
}
Where UnitType
is an Enum.
Tree of units:
public class Unit {
private int healthVolume;
}
class Soldier extends Unit{
private int strength;
}
class Tank extends Unit{
private int armorAmount;
}
Yep, there are arguments that in the first case there is a possibility to add new units with no effort and additional classes. For example in case I have 100 unit types:
First case: I have to write 1 class.
Second case: I have to write at least 101 classes.
But this String
from Map<String, Object>
don't seem to be nice at all because hard coding of properties name isn't a good style. Adding an Enum will slightly improve the code, but there is also this Object
that seems to be very strange when there are so many generics around.
Do you have any ideas how can this design be improved? Thank you for help in advance.
Upvotes: 3
Views: 342
Reputation: 398
But this
String
fromMap<String, Object>
don't seem to be nice at all because hard coding of properties name isn't a good style.
You are right and false. I think the author(s) want you to think about design and in some cases it is adequate to do not build a longish class hierarchy. If you need strict typing and access to properties with getter/setter style then using this properties map is a bad idea. If your customer needs a flexible, easy to extent hierarchy not containing complex inheritance trees then this property map is a fast way to get productive.
And using the getter/setter complex type hierarchy you get also hard coded property names!
Upvotes: 1