Before I ask my question, I'm aware of Eric Lippert's Wizard and Warrior series.
I'm trying to understand GRASP, but I'm having a hard time determining if this class violates GRASP.
Suppose if I had the following Character
class:
class Character(ABC):
def __init__(self, name, strength, attributes):
self._name = name
self._strength = strength
self._attributes = attributes
self._inventory = []
self._found_attributes = []
self._cannot_equip = False
self._equipped = True
def add(self, game_object):
self._inventory.append(game_object)
# I may obviously want to do more checks, such as required strength,
# if I currently have another weapon equipped, etc..
def try_equip(self, game_object):
if self._check_for_conflicting_attributes(game_object):
return self._cannot_equip
return self._equipped
def _check_for_conflicting_attributes(self, game_object):
for attrib in self._attributes:
if game_object.contains_attribute(attrib):
self._found_attributes.append(attrib)
return len(self._found_attributes) > 0
Weapon
class:
class GameWeapon(ABC):
# imports and other methods left out.
def __init__(self, name, required_strength, damage, attributes):
self._name = name
self._required_strength = required_strength
self._damage = damage
self._attributes : List[Attributes] = attributes
def contains_attribute(self, attribute):
return attribute in self._attributes
and Main
:
def main():
wizard_attributes : List[Attributes] = []
wizard_attributes.append(Attributes.LongBlade)
wizard_attributes.append(Attributes.Reloadable)
wiz = Wizard("Gandalf", 100, wizard_attributes)
sword_attributes : List[Attributes] = []
sword_attributes.append(Attributes.LongBlade)
sword = Sword("Standard Sword", 5, 10, sword_attributes)
# Will print false
print(wiz.try_equip(sword))
if __name__ == "__main__":
main()
Explanation:
Both Wizard
and Sword
have attributes, for example, Wizard
might have attribute called mana-drinker
and Sword
might have LongBlade
as an attribute. Before adding a LongBlade
weapon to my character inventory, I check for specific attributes, for example, a Wizard can't use a Sword, so I check for LongBlade
and if the weapon has that attribute it will prevent that weapon from being added to the character inventory.
One topic that's always mentioned is class responsibility, if the Character
class does violate GRASP is it because it has the responsibility of checking and verifying if it could add a weapon to the player inventory?
My larger question is, how do you know when a class may be violating GRASP? What if I want the class or subclass to be responsible for check before adding a weapon or doing another task? Is it still a violation?