Does adding values to a dictionary in the constructor violate that “a constructor shouldn't do work”?
https://softwareengineering.stackexchange.com/questions/372930
-
06-02-2021 - |
Question
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?
Solution
This is just more initialization, so it's okay. The point of a constructor to set up the object. This is setting up the object, so it's fine.
When they say "a constructor shouldn't do work" they mean the constructor shouldn't do anything other than setting up the object. For example, the following things are not appropriate for constructors and will eventually cause you headaches down the line:
- Adding an item to a dictionary somewhere else (not part of the object being constructed).
- Creating a file
- Initializing some hardware
- Communicating with a remote system (this may be okay if the remote system's state is not affected)
- Displaying a message on the screen
- Waiting for the user to click a button