'Ensure change of a string doesn't go unnoticed in other spots of a large program

ALL_POSSIBLE_DOG_TOYS is a large list containing the names of every single toy a dog owner can buy for his dog.

ALL_POSSIBLE_DOG_TOYS = ['large_chew_bone', 'treat_ball', .... ]

If the owner has bought a specific toy, it can affect the dog's happiness in various ways depending on some factors (e.g. dog breed, age etc).

Therefore, in some places of my code I need to check whether a specific toy is purchased by the owner, that is, a toy is part of his self.toys_purchased list.

e.g.

# Check if a specific toy is bought.

if 'treat_ball' in self.toys_purchased:
    # Do stuff with treat balls.
    # ...

I need to perform the above checks in various locations of a 15k LOC program. I also want to ensure that if I ever change the name of a toy in ALL_POSSIBLE_DOG_TOYS, I will not forget to also change its name in my if checks.


One way to achieve that is by doing the following:

DOG_TOYS_AS_DICT = {
    'large_chew_bone': 'large_chew_bone',  
    'treat_ball': 'treat_ball',
    ...
    ...
}

That is, create a dict with each key being the same as its value.

Then use DOG_TOYS_AS_DICT values instead of using directly the actual toy name:

# Check if a specific toy is bought.

if DOG_TOYS_AS_DICT['treat_ball'] in self.toys_purchased:
    # Do stuff with treat balls.
    # ...

This way if I ever change 'treat_ball' in ALL_POSSIBLE_DOG_TOYS to 'ball_with_treats' I would get a (desired) KeyError in locations where I # Check if a specific toy is bought, and so that I can change 'treat_ball' to the new string.


Question:
Is there a clearer way to ensure that changes to any of the toy names doesn't go unnoticed in the rest of the program?



Solution 1:[1]

One of the ways - edit your code in IDE, such like PyCharm, so when you need to rename - use refactoring menu, which will change name everywhere in your program.

Solution 2:[2]

Why don't you create an external database, containing the names of those toys, categories, nicknames, article numbers, ...? There seems to be a DB_API library that you can use for accessing MySQL, Oracle, ... databases. Or am I missing something in your question?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Dominique