I am using a factory pattern to get objects that shouldn't be instantiated other than the factory class. These objects are of type ViolationType, which represent violations on a set of rule. Here is the summary of the factory and the available violation types:
class ViolationFactory:
def __init__(self):
raise ValueError('%s cannot be instantiated' % self.__class__.__name__)
class ViolationType:
def __init__(self, name):
self.name = name
_violations = (
ViolationType('RULE_X'),
ViolationType('RULE_Y'),
# the rest of the types...
)
_violations_dict = {v.name: v for v in _violations}
@staticmethod
def get(violation_name):
if violation_name not in ViolationFactory._violations_dict:
raise ValueError('Invalid ViolationType')
return ViolationFactory._violations_dict[violation_name]
A ViolationType is primarily used to instantiate a Violation:
violation = Violation(ViolationFactory.get('RULE_X'), **kwargs)
The problem with this is that if I misspell the string passed to the get() factory method I won't know there is an error until that particular piece of code is ran. So if I try doing ViolationFactory.get('RULE_Z') and such type doesn't exist, it should throw an error when running the program
I think the current design simply doesn't allow such behavior, so: how could I redesign it so that I get a load time error rather than a run time one?