Some what of a followup to this question.
Suppose I have a Player
class with a dictionary call attributes
that holds the Health
and Mana
of the player. In this example, I'll use Python, but my question is language independent as you'll see when you keep reading.
In the Player
constructor, is it okay to add elements to the dictionary?
Example:
class Player:
def __init__(self, name, health, mana):
self._name = name
# Using type hints to indicate the types the dictionary contains
self._attributes: Dict[str,int] = {}
self._attributes["Health"] = health
self._attributesplayer_details["Mana"] = mana
The reason is, it will take a lot of validation to ensure that a correct dictionary is passed to the constructor.
Consider I have to check for the following:
- The dictionary contains the correct number of elements, in this case 2
- Both
Health
andMana
are in the dictionary - The values are set correctly, in this case both are set to 100 at the beginning of the game.
In the above example, I simply have to check that Health
and Mana
don't exceed 100. How it's being stored is of no concern to any outside code.
Does the example violate the guideline that a constructor
shouldn't do work? If so, how should I correct it?